Forcibly break a for loop in sh

8

If I run a for loop on the command line in sh, and I press control-C, it usually cancels the current running process, so I need to hold ^C until the shell itself catches it and breaks the loop. Is there a way to break current process and the loop immediately?

ZimmyDubZongyZongDubby

Posted 2009-09-11T13:16:28.577

Reputation: 375

Answers

12

The easiest way I know would be to suspend the foreground job (^Z), then kill it using the job id (kill %<JOB_ID>).

Example:

[me@host]$ while [ : ]; do less /etc/motd; done   # Ctrl-C can't kill this

After a Ctrl+z

[1]+  Stopped                 less /etc/motd

[me@host]$ kill %1
[me@host]$

The number within the brackets ([1]) at the beginning of the suspension message gives you the job id.

You can also list out ids of suspended jobs using the the jobs command.

Shawn Chin

Posted 2009-09-11T13:16:28.577

Reputation: 1 174