[Linux]ディレクトリ(ファイル)のパーミッションを一括で変更する

linux_logo

この記事には広告を含む場合があります。

記事内で紹介する商品を購入することで、当サイトに売り上げの一部が還元されることがあります。

ディレクトリまたはファイルのパーミッションの一括変更

Linux 環境で作業を行っているとパーミッションを一括で変更したいことがあります。

作業を行っていると色々なパーミッションのファイルが混在していたり、キャッシュの階層のパーミッションに書き込み権限がなかったりと、権限の問題に遭遇します。そんな問題を解決するディレクトリやファイルのパーミッションを一括で変更する方法をお伝えします。

 

パーミッションの変更方法

まずはパーミッションを一括で変更する基本的なコマンドを紹介します。その後に「ディレクトリのみパーミッションを一括で変更する」コマンドと「ファイルのみパーミッションを一括で変更する」コマンドも記載します。

サンプルの書式

chmod -R [権限] [パス]

パーミッションを一括で変更するときは、chmod コマンドに「R」オプションを設定して、コマンドを実行します。

サンプルの実行例

[hoge@hostname]# chmod -R 755 testdir
[hoge@hostname]# ls -la
total 0
drwxr-xr-x. 3 hoge hoge  21 Feb 22 01:16 .
drwx------. 4 hoge hoge 106 Feb 22 01:14 ..
drwxr-xr-x. 2 hoge hoge  56 Feb 22 01:16 testdir
[hoge@hostname]# cd testdir/
[hoge@hostname]# ls -la
total 0
drwxr-xr-x. 2 hoge hoge 56 Feb 22 01:16 .
drwxr-xr-x. 3 hoge hoge 21 Feb 22 01:16 ..
-rwxr-xr-x. 1 hoge hoge  0 Feb 22 01:14 test1.txt
-rwxr-xr-x. 1 hoge hoge  0 Feb 22 01:14 test2.php
-rwxr-xr-x. 1 hoge hoge  0 Feb 22 01:15 test3.rb

 

ディレクトリのパーミッションを一括で変更する

サンプルの書式

find [パス] -type d | xargs chmod [権限]

サンプルの実行例

[hoge@hostname]# find testdir/ -type d | xargs chmod 705
[hoge@hostname]# ls -la
total 0
drwxr-xr-x. 3 hoge hoge  21 Feb 22 01:16 .
drwx------. 4 hoge hoge 106 Feb 22 01:14 ..
drwx---r-x. 3 hoge hoge  70 Feb 22 01:32 testdir
[hoge@hostname]# cd testdir/
[hoge@hostname]# ls -la
total 0
drwx---r-x. 3 hoge hoge 70 Feb 22 01:32 .
drwxr-xr-x. 3 hoge hoge 21 Feb 22 01:16 ..
drwx---r-x. 2 hoge hoge  6 Feb 22 01:32 subdir
-rw-------. 1 hoge hoge  0 Feb 22 01:14 test1.txt
-rw-------. 1 hoge hoge  0 Feb 22 01:14 test2.php
-rw-------. 1 hoge hoge  0 Feb 22 01:15 test3.rb

 

ファイルのパーミッションを一括で変更する

サンプルの書式

find [パス] -type f | xargs chmod [権限]

サンプルの実行例

[hoge@hostname]# find testdir/ -type f | xargs chmod 600
[hoge@hostname]# ls -la
total 0
drwxr-xr-x. 3 hoge hoge  21 Feb 22 01:16 .
drwx------. 4 hoge hoge 106 Feb 22 01:14 ..
drwxr-xr-x. 3 hoge hoge  70 Feb 22 01:32 testdir
[hoge@hostname]# cd testdir/
[hoge@hostname]# ls -la
total 0
drwxr-xr-x. 3 hoge hoge 70 Feb 22 01:32 .
drwxr-xr-x. 3 hoge hoge 21 Feb 22 01:16 ..
drwxr-xr-x. 2 hoge hoge  6 Feb 22 01:32 subdir
-rw-------. 1 hoge hoge  0 Feb 22 01:14 test1.txt
-rw-------. 1 hoge hoge  0 Feb 22 01:14 test2.php
-rw-------. 1 hoge hoge  0 Feb 22 01:15 test3.rb

 

さいごに

パーミッションによる問題に遭遇したときに、本記事が少しでもご参考頂ければ幸いです。

なおコマンドを紹介していますが、Linux 環境では、PHP や Ruby などの開発を行うとき

ディレクトリ:755 または 705
ファイル  :644 または 604
キャッシュ :777 または 770, 700

などに設定されていることが多いです。実際にパーミッションを変更するときは、ご自身の環境に合わせた権限の設定をお願いします。