How to ignore xargs commands if stdin input is empty?

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

    In terms of xargs, you can use -r as suggested, however it's not supported by BSD xargs.

    So as workaround you may pass some extra temporary file, for example:

    find /mydir -type f -name "*.txt" -print0 | xargs -0 chown root $(mktemp)
    

    or redirect its stderr into null (2> /dev/null), e.g.

    find /mydir -type f -name "*.txt" -print0 | xargs -0 chown root 2> /dev/null || true
    

    Another better approach is to iterate over found files using while loop:

    find /mydir -type f -name "*.txt" -print0 | while IFS= read -r -d '' file; do
      chown -v root "$file"
    done
    

    See also: Ignore empty results for xargs in Mac OS X


    Also please note that your method of changing the permissions isn't great and it's discouraged. Definitely you shouldn't parse output of ls command (see: Why you shouldn't parse the output of ls). Especially when you're running your command by root, because your files can consist special characters which may be interpreted by the shell or imagine the file having a space character around /, then the results can be terrible.

    Therefore you should change your approach and use find command instead, e.g.

    find /mydir -type f -name "*.txt" -execdir chown root {} ';'
    

提交回复
热议问题