xargs 與 find 的 -exec 作用類似,但兩者搭配時機不同:xargs 通常透過管道使用,把前面的輸出轉換成後方指令的參數。有了 exec 與 xargs,你就能對 find 匹配到的檔案執行幾乎任何指令。
用法:[find 命令] | [xargs] [其他命令]
功能:從標準輸入建構並執行 shell 命令。與 -exec 類似,會把 find 找到的檔案當作參數交給後續指令。
使用 find 的 -exec 處理匹配檔案時,find 會把所有結果一次交給 exec 執行。但某些系統對可傳遞給 exec 的命令長度有限制,find 跑幾分鐘後就會爆出「參數列太長」或「參數列溢出」的錯誤——這正是 xargs 存在的意義。
find 把結果交給 xargs 後,xargs 每次只取一部分檔案而非全部,因此可以一批一批處理,先處理最先取得的部分,再處理下一批,如此繼續。
另一個差異在效率:某些系統下 -exec 會為每個匹配檔案各發起一個行程,檔案一多就造成行程暴增、系統效能下降;而 xargs 只有一個行程。至於一次取多少參數、是否分批,則由指令選項與核心的可調參數決定。
[root@localhost Documents]# find . -type f -print # 等同 find . -type f,因為預設就輸出到標準輸出
[root@localhost Documents]# find . -type f -print | xargs file ./less1: ASCII text ./newlocate: empty ./findDir/p1.pdf: empty
[root@localhost Documents]# find . -type f | xargs ls -l # 注意:xargs ll 會失敗,因為 ll 只是 ls -l 的別名,並非實際可執行檔 xargs: ll: 沒有那個文件或目錄
[root@localhost Documents]# find . -type f -print | xargs chmod a-x # 回收執行權 [root@localhost Documents]# find . -type f -print | xargs chmod a-r # 回收讀取權
執行 chmod a-r 之後再用 ll 檢視,權限會變成 --w-------,可見批次修改已生效。
[root@localhost sunjimeng]# find ./Document -name "all.txt" -print \
| xargs echo "Success" >/home/sunjimeng/Documents/core.log
[root@localhost sunjimeng]# cat /home/sunjimeng/Documents/core.log
Success ./Document/all.txt[root@localhost sunjimeng]# find ./Document -name "all.txt" | xargs cat \
>/home/sunjimeng/Documents/t3.txt與第 5 例的差別在於:5 輸出的是自訂字串,6 則是把檔案內容複製一份。
[root@localhost sunjimeng]# find ./ -type f | xargs ls -l \
| awk 'BEGIN{size=0}{size+=$5};END{print size}'
5173736[root@localhost Documents]# find . -type f -print | xargs grep "Lost" ./less1:Lost means Get!
值得注意的是,即使當前目錄存在 t3.txt,用 xargs grep "t3.txt" 仍查不到任何結果——因為 grep 比對的是檔案內容而非檔名。
[root@localhost findDir]# find -type f -name "t1.txt" -print | xargs -p mv t2.txt mv t2.txt ./t1.txt ?...n
加上 -p 後,xargs 會在執行前提示是否繼續,輸入 y 才真正執行。這在搭配 mv、rm 這類破壞性指令時相當實用(上例因為 t2.txt 不存在而報錯,屬於示範性質)。