Shell脚本 - 如果子节点无法执行,如何终止父节点

RAJ*_*007 4 linux bash shell

我有一个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
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 5

最简单的机制是:

set -e
Run Code Online (Sandbox Code Playgroud)

这意味着只要子进程以失败状态退出,shell就会退出,除非状态作为条件的一部分进行测试.

例1

set -e
false                        # Exits
echo Not executed            # Not executed
Run Code Online (Sandbox Code Playgroud)

例2

set -e
if false                     # Does not exit
then echo False is true
else echo False is false     # This is executed
fi
Run Code Online (Sandbox Code Playgroud)


Joh*_*024 2

child1.sh && child2.sh && child3.sh
Run Code Online (Sandbox Code Playgroud)

上面的 child2.sh 仅当 child1.sh 成功完成时才执行,child3.sh 仅当 child2.sh 成功完成时才执行。

或者:

child1.sh || exit 1
child2.sh || exit 1
child3.sh || exit 1
Run Code Online (Sandbox Code Playgroud)

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