我正在尝试获取此调用的结果
TMP=$(find /mydir/ -type f -mmin +1440 | xargs rm -f)
M=$?
不幸的是,如果/mydir/
不存在,结果$?
仍然是' 0
',就像没有问题一样。如果什么都不返回,我想得到不是' 0
' 的find
东西。
我应该怎么做?
您可以启用bash
'spipefail
选项。文档(来自help set
):
pipefail the return value of a pipeline is the status of
the last command to exit with a non-zero status,
or zero if no command exited with a non-zero status
所以,你可以写成:
set -o pipefail
TMP=$(find /mydir/ -type f -mmin +1440 | xargs --no-run-if-empty rm -f)
M=$?
set +o pipefail
另外,你为什么在里面执行你的find
命令$( ... )
?如果您不希望它输出错误,请将 STDERR 重定向到/dev/null
,并且最好使用-r
or--no-run-if-empty
标志到xargs
,以避免在它没有从管道接收到任何输入时运行该命令。
检查 bash 中是否存在目录:
if [ ! -d "mydir" ]; then
exit 1 #or whatever you want, control will stop here
fi
TMP=$(find /mydir/ -type f -mmin +1440 | xargs rm -f)
...