Catching SIGINT or Ctl C

suggest change

The trap is reset for subshells, so the sleep will still act on the SIGINT signal sent by ^C (usually by quitting), but the parent process (i.e. the shell script) won’t.


# Run a command on signal 2 (SIGINT, which is what ^C sends)
sigint() {
    echo "Killed subshell!"
trap sigint INT

# Or use the no-op command for no output
#trap : INT

# This will be killed on the first ^C
echo "Sleeping..."
sleep 500

echo "Sleeping..."
sleep 500

And a variant which still allows you to quit the main program by pressing ^C twice in a second:

allow_quit() {
    [ $(date +%s) -lt $(( $last + 1 )) ] && exit
    echo "Press ^C twice in a row to quit"
    last=$(date +%s)
trap allow_quit INT

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents