代码之家  ›  专栏  ›  技术社区  ›  CIsForCookies

bash错误处理程序不退出,但打印错误消息

  •  1
  • CIsForCookies  · 技术社区  · 6 年前

     cp $a $b || (echo "error in line $LINENO (${FUNCNAME[0]})" && exit -1)
    

    我知道它失败了,因为我得到了消息,但是脚本继续运行。 为什么?

    2 回复  |  直到 6 年前
        1
  •  4
  •   chepner    6 年前

    您正在退出由创建的子shell (...) ,而不是您当前的shell。使用 {...}

    cp "$a" "$b" || { echo "..."; exit 1; }
    

    注意:退出状态应为介于0和255之间的整数。

        2
  •  1
  •   Community CDub    4 年前

    我更喜欢坐火车 trap ERR (即命令失败时)。看见 The trap builtin command 对于其他信号,您可以采取行动

    trap cleanup ERR
    

    并将一个简单函数定义为

    cleanup() {
        exitcode=$?
        printf 'exit code returned: %s\n' "$exitcode"
        printf 'the command executing at the time of the error was: %s\n' "$BASH_COMMAND"
        printf 'command present on line: %d\n' "${BASH_LINENO[0]}"
        # Some more clean up code can be added here before exiting
        exit $exitcode
    }
    

    试着运行失败的程序 cp 陷阱 函数中的定义,您可以在其中怀疑可能的故障,而不是全局定义它。

    shell为 陷阱 由脚本中的所有函数继承。看见 The set builtin

    -E

    如已设置,则有 陷阱 在…上 犯错误 在这种情况下,陷阱通常不会遗传。

    set -E
    trap cleanup ERR
    
    cleanup() {
        # clean-up actions
    }
    
    foo() {
        # some incorrect commands
    }
    
    bar() {
        # more incorrect commands
    }
    
    main() {
        foo
        bar
    }