首页 > 解决方案 > 如果任何 subshel​​l 失败,则 Bash 完全失败

问题描述

我想并行运行一些脚本,如果全部成功,我将执行一些额外的命令。但是,如果任何子外壳失败,我想立即退出。

我想用一个例子更容易解释:

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"

上面的脚本打印所有的回声。

标签: bashshell

解决方案


感谢@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"

推荐阅读