首页 > 解决方案 > 如果 find 为空,则不执行下一个命令(xargs --no-run-if-empty)

问题描述

如果 xargs 没有运行,如何防止执行“if/else 条件”?

find $SRC -type f -name 'file_*' | xargs --no-run-if-empty rm -v

if [ $? -eq 0 ] ; then
  echo "removed"
else
  echo "failed to remove"
fi

标签: shell

解决方案


移动if/else里面的shell run inside xargs

xargs sh -c '
    if [ "$#" = 0 ]; then
         echo "no files to remove"
    elif rm -v "$@"; then
        echo "removed"
    else
        echo "failed to remove"
    fi ' --

使用像文件这样的单独实体来传输没有输入的信息。

rm -f /tmp/tempfile

... |
xargs sh -c '
   if [ "$#" = 0 ]; then
        echo "no files to remove" > /tmp/tempfile
   fi
   rm -v "$@" ' --

# or with a separate part in a pipeline that
#   tries to read one line of input
... |
{
  if ! IFS= read -r l; then
     echo "no files to remove" > /tmp/tempfile
  else
     printf "%s\n" "$l"
     cat
  fi
} | xargs --no-run-if-empty rm -v 


ret=$?

if [ -e /tmp/tempfile ]; then
     if [ "$ret" -eq 0 ] ; then
          echo "removed"
     else
         echo "failed to remove"
     fi
fi

在 255 退出状态的情况下,使用GNU xargs的属性返回 124。

... |
xargs sh -c '
   if [ "$#" = 0 ]; then
        exit 255
   fi
   rm -v "$@" ' --

ret=$?

if [ "$ret" -ne 124 ]; then
     if [ "$ret" -eq 0 ] ; then
          echo "removed"
     else
         echo "failed to remove"
     fi
fi

推荐阅读