Technology

Trapping ctrl+c in Bash scripts

If you happen to have some Bash scripts and would like to abort it in clean way there is way to do it. You need to trap ctrl+c command. In case you have some while loop in your scripts, without it, pressing any abort commands is only half way effective.

#!/bin/bash

trap ctrl_c INT

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

while
do
  echo -n "."
done

Now, with ctrl+c trapped, you can cleanly abort your script without things still running.