Tuesday , April 16 2024

How to Catch Ctrl-C in Shell Script

 

To trap Ctrl-C in a shell script, we will need to use the trap shell builtin command. When a user sends a Ctrl-C interrupt signal, the signal SIGINT (Signal number 2) is sent. Let’s see how we can trap this signal in a shell script

 

First, a function trap_ctrlc () is defined in line 4. This function will be called when a Ctrl-C sequence is detected. Any cleanup can be performed in this function. Note the exit statement within the function. Without this statement, the shell script will continue execution.

Second, the trap command is initialised with the function name and the signal to catch in line 18.

Below is the output of the script if we send Ctrl-C while the sleep command is being executed.

 

Now, what if we omit the exit statement in line 13? Below is what we will get.

 

Note that the echo command in line 23 is now being executed.

Loading

About Mikael HOUNDEGNON

My name is Mikael HOUNDEGNON. I am an experienced MySQL DBA/Developer based in the greater Chicago area. You can find out more about me here. I blog here mostly about things I don’t want to forget ? most likely, MySQL Tips. My specialties : MySQL Replication (Master Slave, MultiMaster, Fail over, etc) MySQL Backups MySQL Query Optimization MySQL Performance Tuning MySQL Stored Procedures Storage Engine Tuning Do you have an interesting project idea? Or you just want to chat? Get in touch!

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories