Marius van Witzenburg We fight for our survival, we fight!

18mei/100

How to trap or catch Keyboard Interrupt in Bash on Linux/FreeBSD

Posted by mariusvw

This is a simple code snippet, I think it explains it self.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/bash
 
myCleanup() {
  rm -f /myapp/tmp/mylog
  return $?
}
 
myExit() {
  echo -en "n*** Exiting ***n"
  myCleanup
  exit $?
}
 
trap myExit SIGINT
 
# main loop
while true
do
    echo -n "Enter your name: "
    read x
    echo "Hello $x"
done

If you have any questions, just ask :-)