1

我正在尝试获取此调用的结果

TMP=$(find /mydir/ -type f -mmin +1440 | xargs rm -f)
M=$?

不幸的是,如果/mydir/不存在,结果$?仍然是' 0',就像没有问题一样。如果什么都不返回,我想得到不是' 0' 的find东西。

我应该怎么做?

4

3 回答 3

2

由于 链接

bash 版本 3 引入了一个选项,该选项更改管道的退出代码行为,并将管道的退出代码报告为最后一个程序的退出代码,以返回非零退出代码。只要测试程序后面的程序都没有报告非零退出代码,管道就会将其退出代码报告为测试程序的退出代码。要启用此选项,只需执行:

set -o pipefail

然后

TMP=$(find /mydir/ -type f -mmin +1440 | xargs rm -f)
M=$?

将表现不同并识别错误。另请参阅StackOverflow Best上的上一篇文章,

杰克。

于 2013-07-19T14:43:22.940 回答
1

您可以启用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,并且最好使用-ror--no-run-if-empty标志到xargs,以避免在它没有从管道接收到任何输入时运行该命令。

于 2013-07-19T14:23:06.853 回答
0

检查 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)
...
于 2013-07-19T14:17:32.850 回答