Lately I’ve been working on a pair of more elaborate scripts using ncat and openssl to transfer data between hosts. I’ll get around to posting it eventually, but until then a few small snippets that people may find useful.
Today we will catch ctrl+c and ask the user if he really want’s to terminate the script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #!/bin/bash initialize() { #{{{ # Treat unset variables as an error set -o nounset trap verify_quit INT # verify ending script trap cleanup TERM EXIT # clean up if script exits } #}}} verify_quit() { #{{{ local timeout=10 echo "Press ctrl+c again within ${timeout} seconds to end script" sleep ${timeout} [[ $? -gt 0 ]] && cleanup } #}}} cleanup() { #{{{ exit 0 } #}}} initialize while [ true ] do # do stuff sleep 10 done |
The initialize() and cleanup() are my usual function names I have in every script, making sure general settings and variables are defined and that on exit any tempfiles get deleted.
What has been added was a trap for the INT signal (ctrl+c) which calls the verify_quit() function, giving the user 10 seconds to press ctrl+c again to exit (via cleanup()) or return back to wherever we were in the code. There is one unavoidable caveat, the first ctrl+c will kill whatever the script was doing before it jumps into the verify_quit() function.