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.

2

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
done

And you just echo 1 > mytestfile, if you want to stop the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest