设置-e和后台进程

时间:2017-02-22 10:49:51

标签: bash shell

在我的脚本中,我设置set -e以在发生错误时停止处理。它适用于在前台运行的所有命令,但我的一些命令必须在后台并行运行。 不幸的是,如果后台进程失败,脚本不会停止,尽管set -e标志。

前台进程的示例。

#!/bin/bash
set -e
ls -l no_file
sleep 100

后台进程示例不起作用。

#!/bin/bash
set -e
ls -l no_file &
sleep 100

如何处理后台进程的失败?

1 个答案:

答案 0 :(得分:6)

异步启动命令(使用&)始终返回退出状态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:

$ (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手册的相关部分标题为“作业控制”