bash Shell 脚本:死于任何错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/368744/
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 17:50:43  来源:igfitidea点击:

Shell scripting: die on any error

bashshellscripting

提问by Pistos

Suppose a shell script (/bin/sh or /bin/bash) contained several commands. How can I cleanly make the script terminate if any of the commands has a failing exit status? Obviously, one can use if blocks and/or callbacks, but is there a cleaner, more concise way? Using && is not really an option either, because the commands can be long, or the script could have non-trivial things like loops and conditionals.

假设一个 shell 脚本(/bin/sh 或 /bin/bash)包含几个命令。如果任何命令的退出状态失败,我如何干净地使脚本终止?显然,可以使用 if 块和/或回调,但是有没有一种更简洁、更简洁的方法?使用 && 也不是一个真正的选项,因为命令可能很长,或者脚本可能包含循环和条件等重要内容。

回答by mat

With standard shand bash, you can

使用标准shbash,您可以

set -e

It will

它会

$ help set
...
        -e  Exit immediately if a command exits with a non-zero status.

It also works (from what I could gather) with zsh. It also should work for any Bourne shell descendant.

它也适用于(从我可以收集到的)与zsh. 它也应该适用于任何 Bourne shell 后代。

With csh/tcsh, you have to launch your script with #!/bin/csh -e

使用csh/ tcsh,您必须使用#!/bin/csh -e

回答by Barun

May be you could use:

也许你可以使用:

$ <any_command> || exit 1

回答by f0ster

You can check $? to see what the most recent exit code is..

你可以检查 $? 查看最新的退出代码是什么..

e.g

例如

#!/bin/sh
# A Tidier approach

check_errs()
{
  # Function. Parameter 1 is the return code
  # Para. 2 is text to display on failure.
  if [ "" -ne "0" ]; then
    echo "ERROR #  : "
    # as a bonus, make our script exit with the right error code.
    exit 
  fi
}

### main script starts here ###

grep "^:" /etc/passwd > /dev/null 2>&1
check_errs $? "User  not found in /etc/passwd"
USERNAME=`grep "^:" /etc/passwd|cut -d":" -f1`
check_errs $? "Cut returned an error"
echo "USERNAME: $USERNAME"
check_errs $? "echo returned an error - very strange!"