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.

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