Search code examples
basherror-handlingbackground-process

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.


Solution

  • 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