加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 22:55:04 所属栏目:安全 来源:网络整理
导读:如果一行返回非零结果,我过去使用的每个系统都会继续我的简单bash脚本.一些新的Ubuntu LTS 14.x系统现在在第一次失败时退出.我用了 echo $- 并且e不会出现在列表中.我还应该寻找什么? 添加评论: $declare -f command_not_found_handlecommand_not_found_ha
如果一行返回非零结果,我过去使用的每个系统都会继续我的简单bash脚本.一些新的Ubuntu LTS 14.x系统现在在第一次失败时退出.我用了

echo $-

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

添加评论:

$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 foundn" "$1" 1>&2;
            return 127;
        fi;
    fi
}

解决方法

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

#!/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命令exit 0的error_handler函数.
在上面的示例中,输出将是:

>START
>./new.sh: line 8: non_existent_command: command not found
>ERROR: ./new.sh: line 8: last command exit status: 127

请注意,“START”打印但“END”不打印.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读