Shell脚本--如何在子进程无法执行时终止父进程

6

我有一个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
2个回答

7
最简单的机制是:
set -e

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

示例1

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

Example 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

在上述代码中,只有当child1.sh成功完成时才会执行child2.sh,只有当child2.sh成功完成时才会执行child3.sh。
另一种方法是:
child1.sh || exit 1
child2.sh || exit 1
child3.sh || exit 1

在上面的代码中,父进程会在任何子进程失败后退出。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接