Reputation: 651
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!
Upvotes: 11
Views: 10978
Reputation: 1233
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
Upvotes: 12
Reputation: 8528
Try killing the program in your control_c()
function, e.g.,
pkill my_command
Upvotes: 4