在 Unix shell 脚本中是否可以进行异常处理,其中包括在内部调用另一个脚本

Is Exception handling possible in Unix shell script, which includes calling another scripts internally

我有一个场景,我需要通过从我的 shell 脚本触发另一个外部 bash 文件来获取一些数据。如果我最终从外部 bash 输出任何错误,我的 shell 脚本应该处理并且应该通过回退方法。但我实际上面临着外部 bash 文件的问题,其中 bash returns (exit 1) 在失败的情况下,这导致我的脚本也退出并且从不执​​行回退方法。任何人都可以指导如何处理外部 bash 和 运行 我的回退方法的退出。

不确定这在 sh 中是否有效,但在 bash 中有效。 我用它制作了一个 try / except 工具,但我相信它也可以在这里工作。

#! /bin/bash

try() {
    exec 2> /dev/null
    #direct stderr out to /dev/null

    #main block
    input_function=""

    #fallback code
    catch_function="" 

    #open a sub shell
    (

    #tell it to exit upon encountering an error
    set -e

    #main block
    "$@"

    )

    #if exit code of above is > 0, then run fallback code
    if [ "$?" != 0 ]; then
        $catch_function
    else
        #success, it ran with no errors
        test
    fi

    #put stderr back into stdout
    exec 2> /dev/tty
}

使用它的一个例子是:

try [function 1] except [function 2]

函数 1 是主要代码块,函数 2 是备用 function/block 代码块。 您的第一个函数可以是:

run() {
  /path/to/external/script
}

你的第二个可以是任何你想依赖的东西。 希望这有帮助。