首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >即使在ENV中未设置-e,Bash脚本也会在第一个非零结果后退出

即使在ENV中未设置-e,Bash脚本也会在第一个非零结果后退出
EN

Stack Overflow用户
提问于 2014-12-03 05:12:32
回答 1查看 358关注 0票数 6

如果一行返回非零结果,我过去使用的每个系统都会继续我的简单bash脚本。一些新的Ubuntu LTS 14.x系统现在会在第一次失败时退出。我用过

代码语言:javascript
复制
echo $-

并且e不会出现在列表中。我还应该寻找什么呢?

从评论中添加:

代码语言:javascript
复制
$ declare -f command_not_found_handle
command_not_found_handle ()
{
    if [ -x /usr/lib/command-not-found ]; then
        /usr/lib/command-not-found -- "$1";
        return $?;
    else
        if [ -x /usr/share/command-not-found/command-not-found ]; then
            /usr/share/command-not-found/command-not-found -- "$1";
            return $?;
        else
            printf "%s: command not found\n" "$1" 1>&2;
            return 127;
        fi;
    fi
}
EN

回答 1

Stack Overflow用户

发布于 2015-09-11 22:19:20

在脚本中使用bash 陷阱,请参阅以下bash脚本示例:

代码语言:javascript
复制
#!/usr/bin/bash

main() {
    trap 'error_handler ${LINENO} $?' ERR
    ###### put your commands in the following
    echo "START"

    non_existent_command

    echo "END"
}

error_handler() {
    process="$0"
    lastline="$1"
    lasterr="$2"
    printf 'ERROR: %s: line %s: last command exit status: %s \n' "$process" "$lastline" "$lasterr"
    trap - ERR
    exit 0
}

main

如果您试图启动一个不存在的命令(在本例中为non_existent_command)或一个退出状态不为0的命令,陷阱将激活包含退出命令exit 0error_handler函数。在上面的示例中,输出将是:

代码语言:javascript
复制
>START
>./new.sh: line 8: non_existent_command: command not found
>ERROR: ./new.sh: line 8: last command exit status: 127

请注意,打印的是"START“而不是"END”。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27259051

复制
相关文章

相似问题

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