Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop linux bash script when a background job fails

How to be noticed when a background job failed (through any signal SEGV, ABRT, KILL, INT ...), when the job is in the background in a linux bash script.

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

does not work.

like image 210
user877329 Avatar asked Feb 04 '26 03:02

user877329


1 Answers

That can help

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
like image 85
Vadim Beskrovnov Avatar answered Feb 06 '26 16:02

Vadim Beskrovnov