考虑这个命令:
ls /mydir/*.txt | xargs chown root
目的是将所有文本文件的所有者更改mydir
为root
问题是,如果没有.txt
文件,mydir
则xargs会发出一条错误,指出没有指定路径。这是一个无害的例子,因为抛出了错误,但在某些情况下,就像我需要在这里使用的脚本一样,空白路径被假定为当前目录。因此,如果我/home/tom/
从那时起运行该命令,如果没有结果,ls /mydir/*.txt
并且所有文件/home/tom/
都将其所有者更改为root。
那么我如何让xargs忽略空结果呢?
发布于 2019-05-31 09:48:30
man xargs
说--no-run-if-empty
。
发布于 2019-05-31 11:07:06
非GNU的xargs用户可以利用的-L <#lines>
,-n <#args>
,-i
,和-I <string>
:
ls /empty_dir/ | xargs -n10 chown root # chown executed every 10 args or fewer
ls /empty_dir/ | xargs -L10 chown root # chown executed every 10 lines or fewer
ls /empty_dir/ | xargs -i cp {} {}.bak # every {} is replaced with the args from one input line
ls /empty_dir/ | xargs -I ARG cp ARG ARG.bak # like -i, with a user-specified placeholder
请记住,xargs在空白处拆分行,但引用和转义是可用的; RTFM了解详情。
此外,正如Doron Behar所提到的,这种解决方法不可移植,因此可能需要进行检查:
$ uname -is
SunOS sun4v
$ xargs -n1 echo blah < /dev/null
$ uname -is
Linux x86_64
$ xargs --version | head -1
xargs (GNU findutils) 4.7.0-git
$ xargs -n1 echo blah < /dev/null
blah
https://stackoverflow.com/questions/-100001412
复制相似问题