2

I ran a command:

while true ; do ..... ....... ; done

on the Linux console/terminal, and now this while loop is continuously running.

I have two questions here:

  1. How to get out of this while loop?
  2. If my PuTTY session to Linux gets disconnected, how can I go back and find this loop and kill it?
3

You can cancel the loop with: CTRL + C

Your session would have ended when your putty session closed so the loop will no longer be running

  • unless it was running in a screen session or similar in which case you would have to reattach it using the method of that particular program.
1

Sometimes hitting control-c doesn't work: the loop body gets the control-c and the loop keeps iterating. (Although I can't reproduce this behaviour right now with sleep 1 as the loop condition or the body, I remember seeing it.)

control-z can stop this, and the loop won't resume after fg unless the loop was inside a subshell like (while true;do : ;done). (With bash on GNU/Linux).

Or control-z / fg is useful if you want the currently-running iteration of the loop to finish cleanly, but not start another iteration.

(Control-z stops a job, getting the kernel to deliver SIGTSTP exactly like how control-c delivers SIGINT, on a TTY that's not in raw mode. The default action for this signal is to stop the job. fg and bg are job-control commands, see the bash built-in "help" for them and the jobs command.)

1

Given what @PeterCordes correctly points out, that Ctrl-C doesn't always work, a solution I sometimes use is to avoid making the loop infinite. Instead, I often write:

while sleep 1; do ...; done

If that one-second delay is too much of a slowdown, such as when you want to loop as quickly as possible, then condition the while loop on the presence of a semaphore file:

touch /tmp/ENABLE-LOOP-FILE
while [ -f '/tmp/ENABLE-LOOP-FILE' ]; do ...; done

When you need to kill the loop, go to another terminal session and remove the file:

rm /tmp/ENABLE-LOOP-FILE

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.