Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH - Trap Ctrl+C to clean process before quiting

I want to trap Control + C in my script so that I can do some cleaning before I quit the script. I have this so far:

trap ctrl_c INT

main_script() {
   #State of the art technology happening here
}

ctrl_c() {
   #Do some cleaning
   exit 1
}

The problem is that after I press Control + C and get back to console, The console behaves abnormally. I cannot see my keyboard entries anymore and pressing enter doesn't go to a new line. For example, this is what my console looks like:

root@ZonkedCream:~# root@ZonkedCream:~# root@ZonkedCream:~#

Help is appreciated

like image 869
Kousha Avatar asked Jan 18 '26 12:01

Kousha


1 Answers

We don't have the source code of your script so... Just guessing.

Probably you script changes stty settings somehow and they were not restored when you break the application with CTRL-C.

I'd suggest you to save your stty flags as soon as your script starts and restore them in your ctrl_c() function or - at least - use stty sane in ctrl_c() before quitting.

like image 105
mauro Avatar answered Jan 21 '26 05:01

mauro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!