差別描述: 兩者都是對符合條件的檔案執行所給的Linux 指令,而不詢問使用者是否需
要執行該指令。
-exec:{}表示指令的參數即為所找到的檔案,以;表示comman指令的結束。\是轉義符,
因為分号在指令中還有它用途,是以就用一個\來限定表示這是一個分号而不是表示其它意思。
-ok: 和 -exec 的作用相同,格式也一樣,隻不過以一種更為安全的模式來執行該參數
所給出的shell給出的這個指令之前,都會給出提示,讓使用者來确定是否執行。
xargs 要結合管道來完成
格式:find [option] express |xargs command
用一個執行個體來看看exec和xargs是如何傳參數的:
$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是對每個找到的檔案執行一次指令,除非這單個的檔案名超過了幾k,否則不
會出現指令行超長出報錯的問題。
而xargs是把所有找到的檔案名一股腦的轉給指令。當檔案很多時,這些檔案名組合成的命
令行參數很容易超長,導緻指令出錯。
另外, find | xargs 這種組合在處理有空格字元的檔案名時也會出錯,因為這時執行的指令
已經不知道哪些是分割符、哪些是檔案名中的空格! 而用exec則不會有這個問題。
比如做個示範:
$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 {} ;
相比之下,也不難看出各自的缺點
1、exec 每處理一個檔案或者目錄,它都需要啟動一次指令,效率不好;
2、exec 格式麻煩,必須用 {} 做檔案的代位符,必須用 ; 作為指令的結束符,書寫不便。
3、xargs 不能操作檔案名有空格的檔案;
綜上,如果要使用的指令支援一次處理多個檔案,并且也知道這些檔案裡沒有帶空格的檔案,
那麼使用 xargs比較友善; 否則,就要用 exec了。