【问题标题】:Automatic exit from bash shell script on error: set +e does not seem to do the job发生错误时自动退出 bash shell 脚本:set +e 似乎不起作用
【发布时间】:2017-01-10 15:18:57
【问题描述】:

虽然我知道 shell 脚本不关心错误已有 20 年了,但默认情况下,我一直对这种粗心大意感到好笑。即使您明确要求他们不要吞下错误并遵循仍然不会发生的崩溃早期原则。

参考Automatic exit from bash shell script on errorset +e 似乎不起作用,这里有一个简短的例子:

#!/bin/bash -vx
set +e
apt-get install nonexisting1
apt-get install nonexisting2
set -e

输出:

#!/bin/bash -vx
set +e
+ set +e
apt-get install nonexisting1
+ apt-get install nonexisting1
Reading package lists... Done
Building dependency tree       
Reading state information... Done
E: Unable to locate package nonexisting1  <--- first error, now stop!
apt-get install nonexisting2           <--- why do we continue here?
+ apt-get install nonexisting2
Reading package lists... Done
Building dependency tree       
Reading state information... Done
E: Unable to locate package nonexisting2
set -e
+ set -e

如何确保我的脚本执行所有命令都没有错误或立即停止? 我不喜欢在几乎每一行的末尾写|| exit 1

【问题讨论】:

  • set +e 将选项关闭

标签: linux bash shell ubuntu error-handling


【解决方案1】:

我猜你只是使用 set +e 代替 set -e ,反之亦然。 如果你只是这样做

#!/bin/bash -vx
set -e
apt-get install nonexisting1
apt-get install nonexisting2
set +e

它应该在第一行之后停止。

【讨论】:

    【解决方案2】:

    shell 中的选项(与直觉相反)使用减号打开并使用加号关闭。

    即便如此,set -e 选项只有在程序正确返回非零错误状态时才有效。

    虽然apt-get 手册说它应该这样做,但其他帖子表明它经常不这样做(参见apt-get update exit status)。

    在运行后验证 apt 命令的返回状态(例如,使用 echo $?)。如果它返回非零,set -e 应该可以工作。

    【讨论】:

      【解决方案3】:

      为什么要在脚本前面设置“+e”?
      这是我的例子:

      #!/bin/bash  -xv
      
      set -e 
      
      dskakj
      
      echo "Hello dear" 
      apt-get install bash
      

      输出:

      #!/bin/bash  -xv
      
      set -e 
      + set -e
      
      dskakj
      + dskakj
      ./a.sh: line 5: dskakj: command not found
      

      注意:不需要在脚本末尾设置“+e”。

      【讨论】:

        【解决方案4】:

        对于像你这样的四行脚本,set -e 确实感觉合理,假设 apt-get 确实以非零退出代码退出错误。

        然而,关于 SO 上的set -e 的大量讨论表明它不是一种可靠的错误处理技术。 Bash 文档证实了这一点。

        如果我们希望脚本可靠,我们别无选择,只能在每个命令后检查状态变量 $?

        【讨论】:

          猜你喜欢
          • 2011-02-21
          • 1970-01-01
          • 1970-01-01
          • 2011-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-16
          相关资源
          最近更新 更多