You'd need to put that code into an infinite loop, such as:
while 1; do # Rest of code ... done
In order to stop when Ctrl+C is hit, what you're actually doing is to trap a signal (concretely, SIGINT
). You'd need to define a trap
so it triggers when you hit that combination of keys.
For more info about traps, you can have a look here, which includes a SIGINT
example and how you can print anything after catching it.
trap [COMMANDS] [SIGNALS]
This instructs the trap command to catch the listed SIGNALS, which may be signal names with or without the SIG prefix, or signal numbers. If a signal is 0 or EXIT, the COMMANDS are executed when the shell exits. If one of the signals is DEBUG, the list of COMMANDS is executed after every simple command. A signal may also be specified as ERR; in that case COMMANDS are executed each time a simple command exits with a non-zero status. Note that these commands will not be executed when the non-zero exit status comes from part of an if statement, or from a while or until loop. Neither will they be executed if a logical AND (&&) or OR (||) result in a non-zero exit code, or when a command's return status is inverted using the ! operator.