我有一个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)
最简单的机制是:
set -e
Run Code Online (Sandbox Code Playgroud)
这意味着只要子进程以失败状态退出,shell就会退出,除非状态作为条件的一部分进行测试.
set -e
false # Exits
echo Not executed # Not executed
Run Code Online (Sandbox Code Playgroud)
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)
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)
在上面的例子中,父脚本在任何子脚本失败后退出。
| 归档时间: |
|
| 查看次数: |
1227 次 |
| 最近记录: |