提示:閱讀這篇之前,建議先弄清楚 Linux 檔案與目錄的權限模型(rwx、所屬者/群組/其他人)。
chmod [選項]... 模式[,模式]... 檔案...
或:chmod [選項]... 八進位模式 檔案...
或:chmod [選項]... --reference=參考檔案 檔案...
它的作用是把每個檔案的權限模式改為指定值。
-c, --changes:類似 --verbose,但只在真的發生變更時才輸出結果。
--no-preserve-root:不對根目錄做特殊保護(預設行為)。
--preserve-root:禁止對根目錄進行遞迴操作。
-f, --silent, --quiet:抑制大部分錯誤訊息。
-v, --verbose:為每個處理過的檔案顯示診斷資訊。
--reference=參考檔案:直接沿用參考檔案的權限模式,不自行指定。
-R, --recursive:遞迴處理所有檔案與子目錄。
--help:顯示說明並結束。
--version:顯示版本資訊並結束。
模式(MODE)的通用形式為 "[ugoa]*([-+=]([rwxXst]*|[ugo]))+"。
1. 為檔案加上執行權限
三種等價寫法:chmod u+x test、chmod 751 test、chmod u=rwx,g=r,o=r test。
[root@localhost cmd_chmod]# ls -l
-rw-r--r--. 1 root root 0 5月 13 12:41 test
[root@localhost cmd_chmod]# chmod u+x test
[root@localhost cmd_chmod]# ls -l
-rwxr--r--. 1 root root 0 5月 13 12:41 test
2. 遞迴為目錄及其內部檔案加上權限
[root@localhost cmd_chmod]# ls -l
-rw-r--r--. 1 root root 0 5月 13 12:41 test
-rw-r--r--. 1 root root 0 5月 13 12:56 test1
[root@localhost cmd_chmod]# cd ..
[root@localhost Mydir]# chmod -R u+x cmd_chmod
[root@localhost Mydir]# cd cmd_chmod
[root@localhost cmd_chmod]# ls -l
-rwxr--r--. 1 root root 0 5月 13 12:41 test
-rwxr--r--. 1 root root 0 5月 13 12:56 test1
小結:符號模式適合「在既有權限上微調」,八進位模式適合「一次設定完整權限」,而 --reference 則在需要讓多個檔案與某個範本檔案保持一致時特別方便。加上 -R 之前請務必確認目標路徑,遞迴操作一旦打錯目錄,後果往往不易收拾。