问题描述
考虑这个命令:
ls /mydir/*.txt | xargs chown root
目的是将mydir
中所有文本文件的所有者更改为root
The intention is to change owners of all text files in mydir
to root
问题是,如果 mydir
中没有 .txt
文件,那么 xargs 会报错,说没有指定路径.这是一个无害的示例,因为正在引发错误,但在某些情况下,例如在我需要在此处使用的脚本中,假定当前目录为空白路径.因此,如果我从 /home/tom/
运行该命令,那么如果 ls/mydir/*.txt
和 /home/下的所有文件都没有结果tom/
已将其所有者更改为 root.
The issue is that if there are no .txt
files in mydir
then xargs thows an error saying there is no path specified. This is a harmless example because an error is being thrown, but in some cases, like in the script that i need to use here, a blank path is assumed to be the current directory. So if I run that command from /home/tom/
then if there is no result for ls /mydir/*.txt
and all files under /home/tom/
have their owners changed to root.
那么如何让 xargs 忽略空结果?
So how can I have xargs ignore an empty result?
推荐答案
对于 GNU xargs
,可以使用 -r
或 --no-run-if-empty
选项:
For GNU xargs
, you can use the -r
or --no-run-if-empty
option:
--no-run-if-empty
-r
如果标准输入不包含任何非空格,请不要运行该命令.通常,即使没有输入,该命令也会运行一次.此选项是 GNU 扩展.
--no-run-if-empty
-r
If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension.
xargs
的 BSD 版本在 macOS 上使用,不会对空输入运行命令,因此不需要 -r
选项(也不需要它被那个版本的 xargs
接受).
The BSD version of xargs
, which is used on macOS, does not run the command for an empty input, so the -r
option is not needed (nor is it accepted by that version of xargs
).