shell 命令使用 & 操作符,怎么知道是否有命令失败。

比如

commandA & commandB & commandC & wait
# 在这个地方怎么知道上面这三个命令有没有失败的
阅读 1.5k
1 个回答

你直接这么wait是不行的,你得wait这几个后台进程的pid才行

$ commandA &
$ pid1=$!
$ commandB &
$ pid2=$!
$ commandC &
$ pid3=$!
$ wait $pid1 $pid2 $pid3

这样如果任意一个失败则退出码都不是0,最后一个错误退出的退出码应该就是wait的退出码。更完整的wait使用你应该看wait --help或者man wait,有更多范例

Stackoverflow有更完整的范例和解释: https://stackoverflow.com/que...

看看人家的范例,写的非常漂亮:

# simulate a long process that will have an identifiable exit code
(sleep 15 ; /bin/false) &
my_pid=$!

while   ps | grep " $my_pid "     # might also need  | grep -v grep  here
do
    echo $my_pid is still in the ps output. Must still be running.
    sleep 3
done

echo Oh, it looks like the process is done.
wait $my_pid
# The variable $? always holds the exit code of the last command to finish.
# Here it holds the exit code of $my_pid, since wait exits with that code. 
my_status=$?
echo The exit status of the process was $my_status
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进