首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >出错时退出脚本

出错时退出脚本
EN

Stack Overflow用户
提问于 2010-12-08 05:10:38
回答 4查看 207.8K关注 0票数 163

我正在构建一个外壳脚本,它具有如下所示的if函数:

代码语言:javascript
复制
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

...

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-12-08 05:13:49

你在找exit吗?

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

在上下文中:

代码语言:javascript
复制
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

...
票数 164
EN

Stack Overflow用户

发布于 2010-12-08 13:12:40

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

代码语言:javascript
复制
#!/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

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

票数 45
EN

Stack Overflow用户

发布于 2014-03-05 23:43:35

以下是实现此目的的方法:

代码语言:javascript
复制
#!/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 *** 
************
'
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4381618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档