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!
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.
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.
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
Try killing the program in your control_c()
function, e.g.,
pkill my_command
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With