shell - 如果 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
解决方案
移动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
推荐阅读
- c# - 检查组框中的所有按钮是否都被禁用
- php - 如何将图像文件夹与 php 中的 csv 文件进行比较?
- java - 为什么 Java 上的 instanceof 会出现编译错误?
- json - Azure Policy:标记定义资源是否可以移动/部署到特定位置
- python - 使用 TQDM 的 Telegram Telethon 媒体下载进度
- angular - Angular Form Array如何检测表单值的变化
- build - 如何停止在 Circle CI 中提交代码时触发的所有构建
- javascript - redux 表单的验证功能没有被触发
- python - python多进程:父进程无法退出
- c# - “帐户”不包含“提款”的定义,并且没有可访问的扩展方法“提款”错误