How to force quit out of an infinite loop in a bash script gracefully
I wrote a bash script that logs keycodes in a simple file. I have put the code in a while loop because I want it to log continuosly. But if I run the bash script in the terminal, the cursor just keeps blinking suggesting that the file is indeed caught in an infinte loop. Now i want to be able to quit this loop gracefully. I don't know how. Ctrl+C won't work. I just close the terminal and force quit the process. How do i break out of the while loop as and when the user feels like quitting the program?
3 Answers
If you get a blinking cursor you are probably not actually in a loop. You are probably expecting input. Try Ctrl+D. If that doesn't work then open a new terminal and ps aux | grep command where command is the name of the script you wrote and then kill the pid that is returned.
As suggested by this answer or this more detailed one to similar questions on unix.stackexchange.com :
- Press Ctrl+Z to stop the job, and send it to the background
kill %%to kill the "current" or "last stopped" job
Just an idea. What if you read value from a file, and instead an infinite loop, you test the value? Something like this:
while [ "`cat mytestfile`" = 0 ]; do //your stuff here
doneAnd you just echo 1 > mytestfile, if you want to stop the loop.