I used to write my scripts like this:
some_command while [ $? -ne 0 ] ; do sleep 1 some_command done
It always irked me that I have to write
some_command twice. Can I put it inside the loop test section somehow?
You could use
some_command as your test condition.
while ! some_command; do sleep 1; done
The condition will remain true as long as
some_command exits with an error.
Or a more verbose way if you want to do additional checks:
while ! some_command do # add more if desired sleep 1 done
This is what the
until loop is for:
until some_command do sleep 1 done
It is the logical negation of a
The spec says:
until loop shall continuously execute one compound-list as long as another compound-list has a non-zero exit status.
The format of the until loop is as follows:
until compound-list-1 do compound-list-2 done
untilcommand completes. Otherwise, the compound-list-2 shall be executed, and the process repeats.
You can just do:
false while [ $? -ne 0 ] ; do sleep 1 some_command done
this has the disadvantage though that it always sleeps one second first
If you want to be able to exit on any of a number of commands to exit with 0 you can do :
while true; do if [ some_command ] ; then break ; fi if [ some_other_command ] ; then break ; fi sleep 1 done
which of course also works for just
while ! ... nor
until ... works on the systems that froze their shell environment prior to POSIX.1-2001. This, however, does.
while :; do if some command; then break fi sleep 1 done
If you don't need total portability, why are you writing a shell script? Perl is more likely to be available than Bash.
sleep 1 while 0 != system qw(some command);
(As above, the
sleep is only executed if the command fails.)