Trapping ctrl-c in Bash

You can use the trap builtin to handle a user pressing ctrl-c during the execution of a Bash script. e.g. if you need to perform some cleanup functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash

# trap ctrl-c and call ctrl_c()
trap ctrl_c INT

function ctrl_c() {
echo "** Trapped CTRL-C"
}

for i in `seq 1 5`; do
sleep 1
echo -n "."
done