从错误的bash shell脚本自动退出 [英] Automatic exit from bash shell script on error

查看:408
本文介绍了从错误的bash shell脚本自动退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在写一些shell脚本,我会觉得如果有用的话有说shell脚本,如果任何命令未能阻止执行的能力。请参见下面的例子:

I've been writing some shell script and I would find it useful if there was the ability to halt the execution of said shell script if any of the commands failed. See below for an example:

#!/bin/bash  

cd some_dir  

./configure --some-flags  

make  

make install

因此​​,在这种情况下,如果脚本不能改变到指定目录,然后它当然不希望以后做的./configure,如果它失败。

So in this case if the script can't change to the indicated directory then it would certainly not want to do a ./configure afterwards if it fails.

现在我很清楚,我可以有一个,如果检查每个命令(我认为这是一个没有希望的解决方案),但有一个全球性的设置,使脚本退出,如果其中一个命令失败?

Now I'm well aware that I could have an if check for each command (which I think is a hopeless solution), but is there a global setting to make the script exit if one of the commands fails?

推荐答案

使用的 设置-e 内置:

Use the set -e builtin:

#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately

另外,你可以通过 -e 在命令行上:

bash -e my_script.sh

您还可以禁用与组+ E 。这种行为

You can also disable this behavior with set +e.

(*)注:

壳做的的退出,如果失败的命令是部分
  命令列表紧跟在,而直到关键字的一部分,
  测试在如果语句,一个&功放的一部分;&安培; || 列表,或者
  命令的返回值正在通过倒

The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or || list, or if the command's return value is being inverted via !

(从男人庆典

这篇关于从错误的bash shell脚本自动退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆