Tell me more ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a command that I want to have run again automatically each time it terminates, so I ran something like this:

while [ 1 ]; do COMMAND; done;

but if I can't stop the loop with Ctrl-c as that just kills COMMAND and not the entire loop.

How would I achieve something similar but which I can stop without having to close the terminal?

share|improve this question
2  
@jw013 That should be an answer. Works nicely for my purposes. – howardh Jul 4 '12 at 3:06
3  
If I'm in bash I just use Ctrl-Z to stop the job and then "kill %1" to kill it. – Paul Cager Jul 4 '12 at 13:20
1  
Just wait... Linus was quoted as saying: “We all know Linux is great... it does infinite loops in 5 seconds.” -- so really... just wait a few more seconds, it should complete. – lornix Jul 5 '12 at 8:40

4 Answers

up vote 8 down vote accepted

Check the exit status of the command. If the command was terminated by a signal the exit code will be 128 + the signal number. For example if you interrupt a command with control-C the exit code will be 130, because SIGINT is signal 2 on Unix systems. So:

while [ 1 ]; do COMMAND; test $? -gt 128 && break; done
share|improve this answer
3  
It should be mentioned that this is not guaranteed, in fact, many applications will not do this. – Chris Down Jul 4 '12 at 1:18

I generally just hold down Ctrl-C. Sooner or later it'll register between COMMAND's and thus terminate the while loop. Maybe there is a better way.

share|improve this answer

I would say it might be best to put your infinite loop in a script and handle signals there. Here's a basic starting point. I'm sure you'll want to modify it to suit. The script uses trap to catch ctrl-c (or SIGTERM), kills off the command (I've used sleep here as a test) and exits.

cleanup ()
{
kill -s SIGTERM $!
exit 0
}

trap cleanup SIGINT SIGTERM

while [ 1 ]
do
    sleep 60 &
    wait $!
done
share|improve this answer
Nice. Here's how I used this tip to make an autorestarting netcat wrapper: trap "exit 0" SIGINT SIGTERM; while true; do netcat -l -p 3000; done – Douglas Jan 13 at 13:00

If you run bash with -e it will exit on any error conditions:

#!/bin/bash -e
false # returns 1
echo This won't be printed
share|improve this answer
This will definitely come in handy. – Dean Jul 4 '12 at 7:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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