How to ignore xargs commands if stdin input is empty?

后端 未结 6 2054
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 04:29

Consider this command:

ls /mydir/*.txt | xargs chown root

The intention is to change owners of all text files in mydir to root

6条回答
  •  臣服心动
    2020-11-28 05:16

    Users of non-GNU xargs may take advantage of -L <#lines>, -n <#args>, -i, and -I :

    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
    

    Keep in mind that xargs splits the line at whitespace but quoting and escaping are available; RTFM for details.

    Also, as Doron Behar mentions, this workaround isn't portable so checks may be needed:

    $ 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
    

提交回复
热议问题