在我的脚本中,我设置set -e
为在发生错误时停止处理.它适用于在前台运行的所有命令,但我的一些命令必须在后台并行运行.不幸的是,如果后台进程失败,脚本不会因set -e
标志而停止.
前台进程的示例有效.
#!/bin/bash
set -e
ls -l no_file
sleep 100
Run Code Online (Sandbox Code Playgroud)
后台进程的示例不起作用.
#!/bin/bash
set -e
ls -l no_file &
sleep 100
Run Code Online (Sandbox Code Playgroud)
如何处理后台进程的失败?
异步启动命令(with &
)始终返回退出状态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
Run Code Online (Sandbox Code Playgroud)
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 )
Run Code Online (Sandbox Code Playgroud)
Bash手册的相关部分标题为"作业控制"