Maxim Andreev
Maxim Andreev

Reputation: 197

How to immediately skip loop and go to trap on kill command to process? [BASH]

My script:

#!/bin/bash
finish() {
    echo "[$(date -u)] I was terminated."
    exit
}
trap finish SIGINT SIGTERM
echo "pid is $$"
while true
do
    echo 'I am running'
    sleep 15    
done

When I send command kill -SIGTERM <pid> to the process running my script I have to wait till sleep 15 would be executed. I googled but didn't find any answers how to immediately break out of the loop and go to executing trap when I send kill command.

Upvotes: 0

Views: 1649

Answers (1)

Javier Elices
Javier Elices

Reputation: 2154

This question has been more or less answered here: Linux: How to kill Sleep. In short, the bash shell executing the script gets the kill signal, but the sleep call does not.

If you want a process to sleep you can execute the sleep in the background while you do a wait on it. That way, the parent process will get your signal and be free to deal with it. In your code:

#!/bin/bash
finish() {
    echo "[$(date -u)] I was terminated."
    exit
}
trap finish SIGINT SIGTERM
echo "pid is $$"
while true
do
    echo 'I am running'
    sleep 15 &
    wait
done

Bear in mind that your kill signal will be caught by the parent process which will terminate immediately, but the sleep 15 will still run in the background until it finishes. You may kill this sleeping process by adding kill $! which kills the last background process executed by bash.

One final remark. wait may wait for one or more processes to finish. With no arguments it will wait for all the child processes to finish. It will also return the status of the last process that finished if a process was specified. If not (like in the example), it will return 0.

Upvotes: 5

Related Questions