出错时退出脚本

Nat*_*pos 126 bash shell exit

我正在构建一个具有如下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

...
Run Code Online (Sandbox Code Playgroud)

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

Gil*_*il' 324

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

这种方法的优点在于它是自动的:您不会冒失去处理错误情况的风险.

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

  • 根据http://mywiki.wooledge.org/BashFAQ/105 - 此功能在确定哪些命令的错误代码导致自动退出时具有模糊和错综复杂的历史.此外,"规则从一个Bash版本变为另一个版本,因为Bash试图跟踪这个'特征'的非常滑的POSIX定义".我同意@Dennis Williamson和http://stackoverflow.com/questions/19622198/what-does-set-e-mean-in-a-bash-script - 使用陷阱'error_handler'ERR的接受答案.即使它是一个陷阱! (3认同)
  • 经常使用带有`-e`标志的`-x`标志足以跟踪程序退出的位置.这意味着脚本的用户也是开发人员. (3认同)

Byr*_*ock 124

你在找exit

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

在上下文中:

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

...
Run Code Online (Sandbox Code Playgroud)

  • 如果你喜欢ABS,你会喜欢[BashGuide](http://mywiki.wooledge.org/BashGuide),[BashFAQ](http://mywiki.wooledge.org/BashFAQ)和[BashPitfalls](http ://mywiki.wooledge.org/BashPitfalls). (3认同)

Pau*_*ce. 40

如果您希望能够处理的错误,而不是盲目地退出,而不是使用set -e,使用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
Run Code Online (Sandbox Code Playgroud)

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


sup*_*bra 8

这是做到这一点的方法:

#!/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 *** 
************
'
Run Code Online (Sandbox Code Playgroud)

  • 合成:完全不要打印愚蠢的星号。 (3认同)
  • 将stderr上的任何内容视为问题的指示可能是同等普遍的做法。 (2认同)