Friday, June 3, 2016

cancel script completely on ctrl-c

I found this question interesting: basically how to cancel completely a script and all child processes :


You do this by creating a subroutine you want to call when SIGINT is received, and you need to run trap 'subroutinename' INT.
Example:
#!/bin/bash

int_handler()
{
    echo "Interrupted."
    # Kill the parent process of the script.
    kill $PPID
    exit 1
}
trap 'int_handler' INT

while true; do
    sleep 1
    echo "I'm still alive!"
done

# We never reach this part.
exit 0
 
Taken from: http://serverfault.com/questions/328089/ctrl-c-in-bash-scripts 

No comments:

Post a Comment