Friday, 25 April 2008

Gracefully exit a bash script on ctrl+C

If a user presses control+c to exit your bash script you may wish for the script to preform some tasks before exiting. To do this you can trap the command. You can use trap along with a function to print a message to the user as follows:

trap stopScript INT
stopScript() {
  echo "Exiting script due to user pressing ctrl+c"

  exit
}

By not putting an exit in your function will cause the script to continue, ignoring the ctrl+c from the user.

No comments:

Post a Comment