【问题标题】:Shell script -- How to terminate parent if child fails to executeShell 脚本——如果子进程无法执行,如何终止父进程
【发布时间】:2015-03-13 08:40:48
【问题描述】:

我有一个调用其他 shell 脚本的 shell 脚本(父级)。假设一个子 shell 脚本执行失败,那么父 shell 脚本也应该停止而不执行下一个子 shell 脚本。我怎样才能使这个过程自动化?

例如:

main.sh
//inside the main.sh following code is there
child1.sh //executed successfully
child2.sh //error occurred
child3.sh //Skip this process
//end of main.sh

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    最简单的机制是:

    set -e
    

    这意味着当子进程以失败状态退出时,shell 将退出,除非该状态作为条件的一部分进行测试。

    示例 1

    set -e
    false                        # Exits
    echo Not executed            # Not executed
    

    示例 2

    set -e
    if false                     # Does not exit
    then echo False is true
    else echo False is false     # This is executed
    fi
    

    【讨论】:

      【解决方案2】:
      child1.sh && child2.sh && child3.sh
      

      上面的 child2.sh 只有在 child1.sh 成功完成时才会执行,而 child3.sh 只有在 child2.sh 成功完成时才会执行。

      或者:

      child1.sh || exit 1
      child2.sh || exit 1
      child3.sh || exit 1
      

      在上面,父脚本在任何子脚本失败后退出。

      【讨论】:

        猜你喜欢
        • 2013-11-22
        • 2016-09-29
        • 1970-01-01
        • 2010-11-01
        • 2021-11-08
        • 1970-01-01
        • 2011-12-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多