V

2012-11-26
how NOT to use xargs

What happens in the following snippet if $TEMPFILE is empty?


#!/bin/sh

TEMPFILE=$( tempfile )
find /some/dir -type f -mtime +60 -print0 > $TEMPFILE

num=0
xargs -n 1 -0 ls -Q < ${TEMPFILE} | while read file; do
    num=$(( num + 1 ))
    if [ $num -gt 1000 ]; then
        break
    fi
    file=$( echo "$file" | sed -e 's/^"//; s/"$//; s/\\"/"/g' )
    mv "$file" /some/other/dir/
done

... it will move all files from the current directory to /some/other/dir/.

One workaround is to use the --no-run-if-empty switch for xargs:

  --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.
  (GNU xargs(1))

... we decided to rewrite in perl :)

Permalink | shell.
$HOME
Archives

Tags