Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catching keyboard interrupt

Tags:

bash

scripting

I have a bash script that is executing a program in a loop and reading the output from the program. I wish that when I hit control-c, it terminates the program as well as the script.

I tried this but does not seem to terminate the program.

control_c() {
   exit
}

while true ; do 

    trap control_c SIGINT

    my_command | while read line ; do
       echo $line 
       ...
    done
done

Can someone show me the correct way to accomplish what I have described? Thank you!

like image 335
j.lee Avatar asked Apr 27 '11 20:04

j.lee


People also ask

How do you handle keyboard interrupts?

When the user pushes the ctrl -c key, the following output appears when the software asks for the username. The print statement created for the KeyboardInterrupt exception is printed in the output when the user presses ctrl – c, which is a user interrupt exception.

What is KeyboardInterrupt error?

Keyboard Interrupt Error The KeyboardInterrupt exception is raised when you try to stop a running program by pressing ctrl+c or ctrl+z in a command line or interrupting the kernel in Jupyter Notebook.


2 Answers

You can do something like this:

control_c() {
    kill $PID
    exit
}

trap control_c SIGINT

while true ; do 
   my_command | while read line ; do
   PID=$!
   echo $line 
   ...
done
like image 166
alnet Avatar answered Oct 30 '22 03:10

alnet


Try killing the program in your control_c() function, e.g.,

pkill my_command
like image 20
Russell Davis Avatar answered Oct 30 '22 03:10

Russell Davis