許多管理員認為「給檔案 444 就能防刪除」,卻忽略了 目錄權限才是刪除/重命名的真正守門人。本文透過三個實驗,揭示 w 權限的真實語義:「控制該 inode 所屬資料結構的內容修改權」——對檔案是資料內容,對目錄是目錄項清單。
tester(非 root,屬於 other 類別)echo(寫檔)、cat(讀檔)、mv(改名)、rm(刪除)# 環境
/test (rwx) ← 目錄完整權限
/test/file (r--) ← 檔案唯讀
$ cd /test
$ echo "abc" > file
bash: file: Permission denied # 寫入檔案內容失敗 ✓
$ cat file
hello world! # 讀取成功 ✓
$ mv file file2
$ ls
file2 # 改名成功!✗
$ rm -f file2
$ ls # 刪除成功!✗
結論: mv/rm 操作的是 /test 目錄的內容(目錄項),而非 file inode 的資料區。目錄有 w 即可改名/刪除。
# 環境
/test (r-x) ← 目錄無寫入權限
/test/file (rw-) ← 檔案可寫
$ echo "abc" > file
$ cat file
abc # 寫入檔案內容成功 ✓
$ mv file file2
mv: cannot move 'file' to 'file2': Permission denied # 改名失敗 ✓
$ rm -f file
rm: cannot remove 'file': Permission denied # 刪除失敗 ✓
結論: 目錄缺 w 即可保護檔案不被改名/刪除,無論檔案本身權限如何。
# 環境
/test (rwx)
/test/file (r--)
/test/dir (r-x)
/test/dir/file (rw-)
$ mv file file2 # 成功(父目錄可寫)
$ mv dir dir2 # 成功(父目錄可寫)
$ rm -f file2 # 成功
$ rm -rf dir2
rm: cannot remove 'dir2/file': Permission denied
$ ls -R
.: dir2
./dir2: file # 子目錄與檔案倖存
現象解析:
rm -rf dir2 先遞歸刪除 dir2/file → 需修改 dir2 目錄項 → dir2 無 w 失敗。dir2 遂保留。mv dir dir2 僅修改 /test 目錄項,不觸及 dir 自身內容,故成功。| 操作 | 實際修改的資料結構 | 所需權限 |
|---|---|---|
| 讀取檔案內容 | 檔案 inode 數據區 | 檔案 r |
| 修改檔案內容 | 檔案 inode 數據區 | 檔案 w |
| 執行檔案 | 檔案 inode 數據區 | 檔案 x |
| 列出目錄 | 目錄 inode 數據區(目錄項清單) | 目錄 r |
| 建立/刪除/改名檔案 | 父目錄 inode 數據區 | 父目錄 w + x |
| 進入目錄 | 目錄 inode | 目錄 x |
:w!)的真相vim 對唯讀檔案執行 :w! 時,實際執行:
unlink("file") 刪除原檔案(需父目錄 w)creat("file", mode) 建立同名新檔案若檔案有第二條硬連結,unlink 僅減少 link count,inode 仍存在;vim 偵測到 link count > 1 時會拒絕強制存檔,避免邏輯錯誤(詳見 src/fileio.c)。
chmod 555(r-x)或 chattr +i。chmod 444 或 chattr +i。chmod 2775 (SGID) + ACL,檔案預設 664。chattr +i 雙重保險(連 root 也需解鎖)。權限模型的精髓在於「誰在修改誰的資料結構」。搞清 w 權限作用於該 inode 所屬的資料區,即可推導出所有改名、刪除、建立、移動操作的成敗邏輯。下次設定權限時,請先問自己:「我要保護的是檔案內容,還是目錄結構?」