bash 出错时退出脚本

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

Exit a Script On Error

bashexitshell

提问by Nathan Campos

I'm building a Shell Script that has a iffunction like this one:

我正在构建一个具有如下if功能的 Shell 脚本:

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
    echo $jar_file signed sucessfully
else
    echo ERROR: Failed to sign $jar_file. Please recheck the variables
fi

...

I want the execution of the script to finish after displaying the error message. How I can do this?

我希望在显示错误消息后完成脚本的执行。我怎么能做到这一点?

采纳答案by Byron Whitlock

Are you looking for exit?

你在找exit吗?

This is the best bash guide around. http://tldp.org/LDP/abs/html/

这是最好的 bash 指南。 http://tldp.org/LDP/abs/html/

In context:

在上下文中:

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
    echo $jar_file signed sucessfully
else
    echo ERROR: Failed to sign $jar_file. Please recheck the variables 1>&2
    exit 1 # terminate and indicate error
fi

...

回答by Gilles 'SO- stop being evil'

If you put set -ein a script, the script will terminate as soon as any command inside it fails (i.e. as soon as any command returns a nonzero status). This doesn't let you write your own message, but often the failing command's own messages are enough.

如果您放入set -e一个脚本,脚本将在其中的任何命令失败时立即终止(即,只要任何命令返回非零状态)。这不会让您编写自己的消息,但通常失败的命令自己的消息就足够了。

The advantage of this approach is that it's automatic: you don't run the risk of forgetting to deal with an error case.

这种方法的优点是它是自动的:您不会冒忘记处理错误情况的风险。

Commands whose status is tested by a conditional (such as if, &&or ||) do not terminate the script (otherwise the conditional would be pointless). An idiom for the occasional command whose failure doesn't matter is command-that-may-fail || true. You can also turn set -eoff for a part of the script with set +e.

状态由条件(例如if,&&||)测试的命令不会终止脚本(否则条件将毫无意义)。偶尔失败无关紧要的命令的成语是command-that-may-fail || true. 您还可以使用set -e关闭脚本的一部分set +e

回答by Paused until further notice.

If you want to be able to handle an error instead of blindly exiting, instead of using set -e, use a trapon the ERRpseudo signal.

如果您希望能够处理错误而不是盲目退出,请在伪信号上set -e使用 a而不是使用。trapERR

#!/bin/bash
f () {
    errorCode=$? # save the exit code as the first thing done in the trap function
    echo "error $errorCode"
    echo "the command executing at the time of the error was"
    echo "$BASH_COMMAND"
    echo "on line ${BASH_LINENO[0]}"
    # do some error handling, cleanup, logging, notification
    # $BASH_COMMAND contains the command that was being executed at the time of the trap
    # ${BASH_LINENO[0]} contains the line number in the script of that command
    # exit the script or return to try again, etc.
    exit $errorCode  # or use some other value or do return instead
}
trap f ERR
# do some stuff
false # returns 1 so it triggers the trap
# maybe do some other stuff

Other traps can be set to handle other signals, including the usual Unix signals plus the other Bash pseudo signals RETURNand DEBUG.

可以设置其他陷阱来处理其他信号,包括通常的 Unix 信号加上其他 Bash 伪信号RETURNDEBUG.

回答by supercobra

Here is the way to do it:

这是这样做的方法:

#!/bin/sh

abort()
{
    echo >&2 '
***************
*** ABORTED ***
***************
'
    echo "An error occurred. Exiting..." >&2
    exit 1
}

trap 'abort' 0

set -e

# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0

echo >&2 '
************
*** DONE *** 
************
'

回答by DGH

exit 1is all you need. The 1is a return code, so you can change it if you want, say, 1to mean a successful run and -1to mean a failure or something like that.

exit 1是你所需要的全部。这1是一个返回码,因此您可以更改它,例如,1表示运行成功和-1失败或类似情况。