How to ignore xargs commands if stdin input is empty?

后端 未结 6 2045
爱一瞬间的悲伤
爱一瞬间的悲伤 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:19

    On OSX: Bash reimplementation of xargs dealing with the -r argument, put that e.g. in $HOME/bin and add it to the PATH:

    #!/bin/bash
    stdin=$(cat <&0)
    if [[ $1 == "-r" ]] || [[ $1 == "--no-run-if-empty" ]]
    then
        # shift the arguments to get rid of the "-r" that is not valid on OSX
        shift
        # wc -l return some whitespaces, let's get rid of them with tr
        linecount=$(echo $stdin | grep -v "^$" | wc -l | tr -d '[:space:]') 
        if [ "x$linecount" = "x0" ]
        then
          exit 0
        fi
    fi
    
    # grep returns an error code for no matching lines, so only activate error checks from here
    set -e
    set -o pipefail
    echo $stdin | /usr/bin/xargs $@
    

提交回复
热议问题