代码之家  ›  专栏  ›  技术社区  ›  Notinlist

sh-e:从if的“else”分支收集命令的退出状态

  •  0
  • Notinlist  · 技术社区  · 8 年前

    我们正在使用编写shell脚本 set -e 作为策略,这意味着如果出现任何未处理的非零退出状态,它将退出。

    #!/bin/sh -e
    
    if some_command; then
      experience_happyness
    else
      print error status of some_command to log or standard error
      experience_sadness
      exit 1
    fi
    

    这个 $? 表达式计算结果为 0 在else分支的开头。如果我不运行 some_command 在…内 if 然后,最终的错误将立即终止shell脚本。

    我如何知道程序的退出状态 集合-e 是否在不终止脚本的情况下有效?

    我对 bash 如果是纯的,也有特定的解决方案 sh 解决方案不可用。

    编辑 :我的错。当@“另一个家伙”回答时,我错了,我说了“$?”在else分支的开头计算为0。我试过了,但试的时候犯了一些错误。很抱歉

    我想我们可以保留这个问题,因为这是一个高质量的答案。我们应该吗?

    1 回复  |  直到 8 年前
        1
  •  4
  •   that other guy    8 年前

    美元?表达式在else分支的开头计算为0。

    不,没有。

    #!/bin/sh -e
    
    some_command() { return 42; }
    
    if some_command; then
      echo "Worked"
    else
      echo "Command failed with $?"
      exit 1
    fi
    

    将打印 Command failed with 42

    推荐文章