【问题标题】:Bash script exiting after 1st non-zero result even though -e is not set in ENV即使未在 ENV 中设置 -e,Bash 脚本也会在第一个非零结果后退出
【发布时间】:2015-12-29 12:19:40
【问题描述】:

如果一行返回非零结果,我过去使用的每个系统都会继续我的简单 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 found\n" "$1" 1>&2;
            return 127;
        fi;
    fi
}

【问题讨论】:

  • 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 }
  • 因此,如果您尝试使用任何无法找到的命令,而这些脚本中的任何一个都返回非零值或找不到这些脚本时,您的脚本将退出。您的脚本以什么退出代码退出?在剧本中的哪一点? set -x 向您展示了什么?
  • 您还可以查看是否设置了 ERR 陷阱。这应该出现在set -x
  • 顺便说一句,不确定您所说的“在 ENV 中”是什么意思。 -e 标志不是环境的一部分。

标签: bash exit


【解决方案1】:

在您的脚本中使用 bash trap,请参见下面的 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 0error_handler 函数。 在上面的示例中,输出将是:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 2021-04-21
    • 2017-04-08
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2020-10-03
    • 2016-08-31
    相关资源
    最近更新 更多