Don't call xargs if the previous command doesn't return anything [duplicate]

我只是一个虾纸丫 提交于 2019-12-14 03:56:51

问题


I have the following command that checks if any new files are added and automatically calls svn add on all these files

svn status | grep -v "^.[ \t]*\..*" | grep "^?" | awk '{print $2}' | xargs svn add

But when there are no files, svn add results in a warning.

How to stop from xargs from getting called the previous command doesn't result in any values? The solution needs to work with both GNU and BSD (Mac OS X) versions of xargs.


回答1:


If you're running the GNU version, use xargs -r:

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

http://linux.die.net/man/1/xargs




回答2:


If you're using bash, another way is to just store outputs in arrays. And run svn only if the there is an output.

readarray -t OUTPUT < <(exec svn status | grep -v "^.[ \t]*\..*" | grep "^?" | awk '{print $2}')
[[ ${#OUTPUT[@]} -gt 0 ]] && svn add "${OUTPUT[@]}"



回答3:


I ended up using this. Not very elegant but works.

svn status | grep -v "^.[ \t]*\..*" | grep "^?" && svn status | grep -v "^.[ \t]*\..*" | grep "^?" | awk '{print $2}' | xargs svn add



回答4:


ls /empty_dir/ | xargs -n10 chown root   # chown executed every 10 args
ls /empty_dir/ | xargs -L10 chown root   # chown executed every 10 lines
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

https://stackoverflow.com/a/19038748/1655942



来源:https://stackoverflow.com/questions/18812766/dont-call-xargs-if-the-previous-command-doesnt-return-anything

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!