xargs是什麼鬼

xargs

xargs是什麼,與管道有什麼不同

一直弄不懂,管道不就是把前一個命令的結果作爲參數給下一個命令嗎,那在 | 後面加不加xargs有什麼區別:

管道是實現“將前面的標準輸出作爲後面的標準輸入”
xargs是實現“將標準輸入作爲命令的參數”

你可以試試運行以下代碼看看結果的不同:

echo "--help"|cat
echo "--help"|xargs cat

如果你直接在命令行輸入cat而不輸入其餘的任何東西,這時候的cat會等待標準輸入,因此你這時候可以通過鍵盤輸入並按回車來讓cat讀取輸入,cat會原樣返回。而如果你輸入--help,那麼cat程序會在標準輸出上打印自己的幫助文檔。也就是說,管道符 | 所傳遞給程序的不是你簡單地在程序名後面輸入的參數,它們會被程序內部的讀取功能如scanf和gets等接收,而xargs則是將內容作爲普通的參數傳遞給程序,相當於你手寫了cat --help

xargs常用選項

  • -0 :當sdtin含有特殊字元時候,將其當成一般字符,比如:/'空格等;

xargs常用實例

find /tmp -name core -type f -print | xargs /bin/rm -f

Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces.

find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f

Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled.

find /tmp -depth -name core -type f -delete

Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we
don't need the extra xargs process).

cut -d: -f1 < /etc/passwd | sort | xargs echo

Generates a compact listing of all the users on the system.

xargs sh -c 'emacs "$@" < /dev/tty' emacs

Launches the minimum number of copies of Emacs needed, one after the other, to edit the files listed on xargs' standard input. This example achieves the same effect as BSD's -o option, but in a
more flexible and portable way.

xargs 退出狀態

xargs exits with the following status:

  • 0 if it succeeds
  • 123 if any invocation of the command exited with status 1-125
  • 124 if the command exited with status 255
  • 125 if the command is killed by a signal
  • 126 if the command cannot be run
  • 127 if the command is not found
  • 1 if some other error occurred.

Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章