Catching SIGINT or Ctl+C

Download bash eBook

Example

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.

#!/bin/sh

# 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:

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

Stats

Contributors: 3
2016-07-31
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook