Stop Loop Bash Script in Terminal – How to Terminate a Running Bash Script
bashsignalstrap:
For example,
#!/bin/bash
while :
do
sl
done
How to terminate this bash script?
Best Answer
The program sl purposely ignores SIGINT, which is what gets sent when you press Ctrl+C. So, firstly, you'll need to tell sl not to ignore SIGINT by adding the -e argument.
If you try this, you'll notice that you can stop each individual sl, but they still repeat. You need to tell bash to exit after SIGINT as well. You can do this by putting a trap "exit" INT before the loop.
The continue keyword doesn't mean whatever you think it means. It means continue to the next iteration of a loop. It makes no sense outside of a loop.
I think you're looking for
trap ' ' INT
Since you don't want to do anything upon reception of the signal (beyond killing the foreground job), put no code in the trap. You need a non-empty string, because the empty string has a special meaning: it causes the signal to be ignored.
Best Answer
The program
sl
purposely ignoresSIGINT
, which is what gets sent when you press Ctrl+C. So, firstly, you'll need to tellsl
not to ignoreSIGINT
by adding the-e
argument.If you try this, you'll notice that you can stop each individual
sl
, but they still repeat. You need to tellbash
to exit afterSIGINT
as well. You can do this by putting atrap "exit" INT
before the loop.