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.

Bash
#!/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.

View as Markdown

All the content on this website is licensed under Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0). Cite as: Michał Sobczak, “Trapping ctrl+c in Bash scripts”, 13 August 2022, https://michalasobczak.pl/posts/trapping-ctrlc-in-bash-scripts.html