When your program has some custom interface, you may want to control more what is on screen. You can turn off typing echo and all sort of things. One is preventing exiting from Ctrl+C to stop your program. Though, it is not quite fitting into convention, but you can let it quit gracefully.

The code is very simple, only need to use trap to trap the INT signal for handling:

#!/bin/bash

trap sigint INT

sigint()
{
  # No ^C
  # echo -ne '\b\b  \b\b'
  :
}

while :; do sleep 1; done

That’s all you need to do.

sigint is the command to execute when INT is trapped. It can be command or commands, basically it is executed like eval 'commands', so whatever is valid for eval, you can use with trap.

If you don’t like seeing ^C and echo is still on, you can manually erase the characters with this inelegant way. The code prevents program from quitting, but you can add exit before the end of sigint(). Printing out a nice exiting message to use, then exit gracefully, cleaning up temporarily files or anything you need to handle before leaving.

If you want to exit gracefully in a better method, you should trap EXIT. Your command will be executed right before your program exits, that is when it has just run the very last line, encounter exit command, or forced to exit in any way.

1   Further reading

  • man signal.
  • man trap.
  • help trap.