-exec 與 xargs 都是對符合條件的檔案執行後續指令,且不會逐一詢問使用者是否執行,差別在於參數傳遞的方式。
-exec:{} 代表指令的參數即為找到的那個檔案,以 ; 表示指令結束。\ 是轉義符,因為分號在 shell 中另有用途,所以要跳脫,告訴 shell 這是個普通分號。
-ok:作用與格式和 -exec 相同,只是執行前會先提示,讓使用者確認,屬於更安全的模式。
xargs:必須搭配管線使用,格式為 find [option] express | xargs command。
$ find test/ -type f
test/myfile.name
test/files/role_file
test/files/install_file
$ find test/ -type f | xargs echo
test/myfile.name test/files/role_file test/files/install_file
$ find test/ -type f -exec echo {} \;
test/myfile.name
test/files/role_file
test/files/install_file
很明顯,exec 是對每個找到檔案各執行一次指令;xargs 則是把所有檔名一次打包交給指令。
$ touch test/'test zzh'
$ find test/ -name *zzh
test/test zzh
$ find test/ -name *zzh | xargs rm
rm: cannot remove `test/test': No such file or directory
rm: cannot remove `zzh': No such file or directory
$ find test/ -name *zzh -exec rm {} \;
xargs 在這裡直接出錯,因為它已經分不清哪些是分隔符、哪些是檔名裡的空白;exec 則完全沒這個問題。
1. exec 每處理一個檔案就要啟動一次指令,效率較差。
2. exec 語法繁瑣,必須用 {} 當代位符、用 \; 當結束符,書寫不便。
3. xargs 無法處理檔名含空白的檔案。
結論:若後續指令支援一次處理多個檔案,且確定檔名不含空白,用 xargs 更方便;否則就用 exec。
實務上還有第三個選擇:find ... -print0 | xargs -0 command。print0 以 null 字元分隔檔名,xargs -0 依此解析,空白與特殊字元都不再是問題,同時保留 xargs 的批次效率,是我個人最常用的寫法。