【问题标题】:Shell: analyse return [duplicate]Shell:分析返回[重复]
【发布时间】:2013-07-18 20:31:44
【问题描述】:

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

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

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

我该怎么办?

【问题讨论】:

标签: linux shell


【解决方案1】:

由于link

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

set -o pipefail

然后

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

将表现不同并识别错误。 另请参阅 StackOverflow 上以前的 post

最好的,

杰克。

【讨论】:

    【解决方案2】:

    您可以启用bashpipefail 选项。文档(来自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--no-run-if-empty 标志到 xargs,以避免在未收到时运行命令来自管道的任何输入。

    【讨论】:

      【解决方案3】:

      检查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)
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-02
        • 1970-01-01
        • 2017-10-02
        • 1970-01-01
        • 1970-01-01
        • 2018-12-25
        • 1970-01-01
        • 2019-05-27
        相关资源
        最近更新 更多