使用 find . -name CVS -exec rm -rf {} \; 刪除所有名為 CVS 的目錄時,雖然目錄已被刪除,卻報錯 find: './CVS': No such file or directory。改用 + 結尾 (find . -name CVS -exec rm -rf {} +) 則完美執行無錯誤。本文深入分析兩者差異與根本原因。
| 語法 | 執行方式 | 命令調用次數 |
|---|---|---|
-exec cmd {} \; | 每個匹配檔案單獨執行一次命令 | 匹配檔案數 |
-exec cmd {} + | 將所有匹配檔案作為參數附加到單一命令 | 1 次 (或分批,類似 xargs) |
使用 ; 時,find 先遞歸掃描建立檔案清單,再逐個執行 rm -rf。當處理父目錄下的 CVS 目錄時,rm -rf 會遞歸刪除該目錄及其子目錄。但 find 內部清單仍包含該目錄下的子項目 (如 ./CVS/Entries),後續嘗試對已不存在的子項目執行 rm -rf,導致「No such file or directory」錯誤。
使用 + 時,find 將所有匹配路徑一次傳遞給 rm -rf,由 rm 內部處理遞歸刪除,find 不再對子項目重複執行命令,避免錯誤。
+ 結尾 或改用 -delete 動作 (GNU find 支援):find . -name CVS -delete;,並注意目錄遍歷順序 (可加 -depth 先處理子項目)-execdir 變體更安全:在檔案所在目錄執行命令,減少路徑遍歷風險-exec command {} +
This variant runs the specified command on the selected files,
but the command line is built by appending each selected file name
at the end; the total number of invocations will be much less than
the number of matched files.