如何在shell函数中获得效果并使用“set -e”? [重复]

前端之家收集整理的这篇文章主要介绍了如何在shell函数中获得效果并使用“set -e”? [重复]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Why is bash errexit not behaving as expected in function calls?3个答案set -e(或以#!/ bin / sh -e开头的脚本)对于在出现问题时自动轰炸非常有用。它使我不必错误地检查可能失败的每个命令。

如何在函数内获得相应的内容

例如,我有以下脚本在出错时立即退出并出现错误退出状态:

  1. #!/bin/sh -e
  2.  
  3. echo "the following command could fail:"
  4. false
  5. echo "this is after the command that fails"

输出符合预期:

  1. the following command could fail:

现在我想把它包装成一个函数

  1. #!/bin/sh -e
  2.  
  3. my_function() {
  4. echo "the following command could fail:"
  5. false
  6. echo "this is after the command that fails"
  7. }
  8.  
  9. if ! my_function; then
  10. echo "dealing with the problem"
  11. fi
  12.  
  13. echo "run this all the time regardless of the success of my_function"

预期产量:

  1. the following command could fail:
  2. dealing with the problem
  3. run this all the time regardless of the success of my_function

实际产量:

  1. the following output could fail:
  2. this is after the command that fails
  3. run this all the time regardless of the success of my_function

(即函数忽略set -e)

这可能是预期的行为。我的问题是:如何在shell函数中获得效果并使用set -e?我发现the same question在Stack Overflow之外被问到但没有合适的答案。

从set -e的文档:

When this option is on,if a simple command fails for any of the
reasons listed in Consequences of
Shell Errors or returns an exit status
value >0,and is not part of the
compound list following a while,
until,or if keyword,and is not a
part of an AND or OR list,and is not
a pipeline preceded by the ! reserved
word,then the shell shall immediately
exit.

在您的情况下,false是前面的管道的一部分!和if的一部分。因此解决方案是重写代码,使其不重写。

换句话说,这里的功能没什么特别之处。尝试:

  1. set -e
  2. ! { false; echo hi; }

猜你在找的Bash相关文章