我想并行运行一些脚本,如果一切成功,我会执行一些额外的命令。但是,如果任何子shell失败,我想立即退出。
我想通过一个例子来解释更容易:
exit_in_1() {
sleep 1
echo "This should be the last thing printed"
exit 1
}
exit_in_2() {
sleep 2
echo "This should not be printed"
exit 1
}
exit_in_1 &
exit_in_2 &
echo "This should be printed immediately"
sleep 3
echo "This should not be printed also"
以上脚本打印所有回声。
答案 0 :(得分:1)
感谢@ Mansuro的评论,我解决了我的问题:
exit_later() {
sleep $1
echo "This should be printed twice"
exit $(($1-1))
}
pids=""
for i in {1..10}; do
exit_later $i &
pids+=" $!"
done
echo "This should be printed immediately"
for p in $pids; do
if ! wait $p; then
kill $pids
exit 1
fi
done
echo "This should not be printed"