1. xargs(1)
  2. xargs(1)

NAME

xargs - 从标准输入中读取并执行命令

描述

此手册页描述GNU版本的xargs.

xargs是给命令传递参数的一个过滤器,也是组合多个命令的一个工具.它把一个数 据流分割为一些小块,以方便过滤器和命令一次或者多次进行处理.由此,这个命令 也是后置引用的一个强有力的替换.通常情况下,xargs从管道或者标准输入读取数 据,但是它也能够从文件的输出中读取数据.

xargs的默认命令是echo.这意味着通过管道传递给xargs的输入将会包含换行和空 白,不过通过xargs的处理,换行和空白将被空格取代.

xargs退出可以有如下状态:

  0     如果成功
123     如果任何一个被调用的命令command退出状态为1-125
124     如果命令command退出状态为255
125     如果命令command被信号终止
126     如果不能执行命令command
127     如果命令command没有找到
  1     如果发生其它错误

选项

--null,-0

输入的文件名以null字符结尾.默认情况下文件名以空格结束,该选项下引 号和反斜杠并不特殊处理(所有字符都以字面意思解释).禁止文件尾字符 串,当另一个参数处理.当参数含有空格,引号,反斜杠时很方便.GNU find 的"-print0"选项产生适合这种模式的输出.

--eof[=eof-str],-e[eof-str]

把文件尾字符串设置成eof-str.如果文件尾字符串出现在输入中的某行, 余下的行将被忽略.如果没有"eof-str",就没有文件尾字符串.如果没有这 个选项,文件尾字符串默认是"_".

--help

显示xargs的选项,然后退出.

--replace[=replace-str],-i[replace-str]

把initial-arguments里的所有replace-str替换为从标准输入里读入的名 称.同时,没有用引号括起来的空格不会结束参数.如果没有replace-str, 它默认为"{}"(同‘find-exec’一样).此选项隐含有-x和-l1选项.

--max-lines[=max-lines],-l[max-lines]

每个命令行最多可以有max-lines行非空格输入;max-lines默认是1.后面 跟着的空格会使后面一行逻辑上是一个输入行的继续.此选项隐含有-x选 项.

--max-args=max-args,-nmax-args

每个命令行最多可以有max-args个参数.如果大小超出了(见-s选项)那么 参数个数将会用比max-args小;除非用了-x选项,那么xargs将退出.

--interactive,-p

提示用户是否运行每个命令行,然后从终端读入一行.只有当此行以’y’或’ Y’开头才会运行此命令行.此选项隐含有-t选项.

--no-run-if-empty,-r

如果标准输入不包含任何非空格,将不运行命令.一般情况下,就算没有输 入,命令也会运行一次.

--max-chars=max-chars,-smax-chars

每个命令行最多可以有max-chars个字符,包括命令和初始参数,还包括参 数后面结尾的null.默认是尽可能的大,有20k个字符.

--verbose,-t

在执行之前在标准错误输出显示命令行.

--version

显示xargs的版本号,然后退出.

--exit,-x

如果大小超出(见-s选项)就退出.

--max-procs=max-procs,-P max-procs

同时最多运行max-procs个进程;默认是1.如果max-procs为0,xargs将同时 运行尽可能多的进程.最好同时用-n选项;不然很可能只会做一次exec.

范例

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 −print | xargs /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 −name core −type f −print0 | xargs −0 /bin/rm −f

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).

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

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

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

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 sh -c ’emacs "$@" < /dev/tty’ emacs

参见

find(1L), locate(1L), locatedb(5L), updatedb(1)

  1. March 2015
  2. xargs(1)