bash 在第一个错误时停止

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3474526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:34:52  来源:igfitidea点击:

Stop on first error

bash

提问by Matt Joiner

Possible Duplicate:
Automatic exit from bash shell script on error

可能的重复:
出现错误时自动退出 bash shell 脚本

How can I have bash stop on the first command failure, without putting stuff like this all through my code?

如何在第一个命令失败时让 bash 停止,而不在我的代码中加入这样的东西?

some_prog || exit 1
some_other_prog || exit 1

回答by Alok Singhal

Maybe you want set -e:

也许你想要set -e

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

这告诉 bash 如果任何语句返回非真返回值,它应该退出脚本。使用 -e 的好处是它可以防止错误在本可以更早被发现的情况下滚雪球般地变成严重的问题。同样,为了可读性,您可能需要使用 set -o errexit。