如果stdin输入为空,如何忽略xargs命令? [英] How to ignore xargs commands if stdin input is empty?

查看:87
本文介绍了如果stdin输入为空,如何忽略xargs命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此命令:

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.

这篇关于如果stdin输入为空,如何忽略xargs命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆