当后台作业失败时停止 linux bash 脚本

Stop linux bash script when a background job fails

如何在后台作业失败时注意到(通过任何信号 SEGV、ABRT、KILL、INT ...),当作业在后台时 linux bash 脚本.

set -e
foo &
foo_pid=$!
# Do tasks that requires that foo is running
wait $foo_pid

不起作用。

有帮助

set -e
foo &
foo_pid=$!

# If this script is killed, kill the `cp'.
trap "kill $foo_pid 2> /dev/null" EXIT

while kill -0 $foo_pid 2> /dev/null; do
    # Do smth
    ...
    sleep 1
done

尝试捕获信号并更新为包含时间和日期的文件。

set -e
act() { 
  echo "Caught signal!" > /tmp/file.txt
  echo `date` >> /tmp/file.txt
  exit
}

trap act SIGINT SIGTERM SIGKILL

foo &
foo_pid=$!
# Do tasks that requires that foo is running
wait $foo_pid