在我的脚本中,我将 set -e
设置为在发生错误时停止处理。它适用于所有在前台运行的命令,但我的一些命令必须在后台并行运行。
不幸的是,如果后台进程失败,脚本不会停止,尽管 set -e
标志。
具有前台进程的示例。
#!/bin/bash
set -e
ls -l no_file
sleep 100
带有后台进程的示例不起作用。
#!/bin/bash
set -e
ls -l no_file &
sleep 100
如何处理后台进程失败?
最佳答案
异步启动命令(使用 &
)总是返回退出状态 0。要获取命令的实际退出状态,请使用内置的 wait
。一个简单的例子:
$ (sleep 5; ls -l nofile) &
[1] 3831
$ echo $?
0
$ wait -n
ls: cannot access 'nofile': No such file or directory
[1]+ Exit 2 ( sleep 5; ls --color=auto -l nofile )
$ echo $?
2
wait -n
等待任何 子进程(这可能非常有用)。如果你想等待一个特定的进程,你可以在启动时捕获 PID——它在特殊变量 $!
中——然后按 PID 等待:
$ (sleep 5; ls -l nofile) &
$ myjobpid=$!
$ # do some other stuff in parallel
$ wait ${myjobpid}
ls: cannot access 'nofile': No such file or directory
[1]+ Exit 2 ( sleep 5; ls --color=auto -l nofile )
Bash 手册的相关部分标题为“作业控制”
关于bash - set -e 和后台进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42389106/