Search code examples
bashsignals

wait exits after trap


I need to handle SIGTERM and keep script running.

#!/bin/bash
trap 'echo do-nothing' SIGTERM
sleep 10m &
wait $!

Why after SIGTERM script exits and how to make it run until sleep 10m & is finished?


Solution

  • Signals cause wait to exit with a status equal to the signal number plus 128. To get the real exit status, loop until $? is less.

    #!/bin/bash
    
    trap 'echo trapped' INT TERM
    sleep 10 & pid=$!
    
    while wait $pid; test $? -ge 128
    do echo 'finished wait'
    done
    
    echo bye
    

    Note that test overwrites $? with its own exit status, so if you care about the real exit status from wait, you'll have to create a variable between wait and test.