Stopping a program with space bar

I am working on a rubik's cube stopwatch written in Bash and I would like to stop it by hiting the space bar since CTRL+C is not feasible when you have to terminate it as fast as you can. So is there a way to stop the program just with the space bar? I looked up at the command kill by I couldn't figure out.

The stopwatch part of the code follows along.

TMP0=$(date +%s%N)
while true; do
    TMP1=$(date +%s%N)
    DTMP=$(($TMP1-$TMP0))
    printf "\r$(($DTMP/1000000000)).${DTMP:(-9):2}"
done

Thank you.


It's your terminal who sends SIGINT to the foreground process group when you press Ctrl+c. You can configure it to do this upon any character, but you want to restore the old settings when the script exits.

#!/bin/bash

settings="$(stty -g)"
trap 'stty $settings' EXIT
stty intr ' '

TMP0=$(date +%s%N)
while true; do
    TMP1=$(date +%s%N)
    DTMP=$(($TMP1-$TMP0))
    printf '\r%s' "$(($DTMP/1000000000)).${DTMP:(-9):2}"
done

settings="$(stty -g)" saves the old settings; stty intr ' ' makes the terminal react to Space instead of Ctrl+c; trap 'stty $settings' EXIT is responsible for restoring the old settings when the script exits.

Notes:

  • In the code of the trap, stty $settings is better than stty "$settings" because some implementations of stty may require word splitting. The specification requires stty -g to generate a string safe in terms of word splitting, so the lack of quotes is allowed later.
  • I used printf '\r%s' … because I think a static format and dynamic data fits the "philosophy" of printf better than dynamic format you used.

In case something goes wrong and you find yourself in an interactive shell where Space still generates SIGINT, you need to invoke stty intr ^C by hand. There are spaces in the command, but keep in mind you can still type a literal space character by pressing Ctrl+v Space.