My script fetch_remote_work.sh is quite slow because it connects to a network. I need run it many times until it works.


while [ $? -ne 0 ]

This obviously works well. However, I don't like being obligated to call the first ./fetch_remote_work.sh. I know that in other languages such as , there is a do while loop that runs at least the first iteration. Which would be very clean if it existed in

So my question is: is there a cleaner way than what I did?


Use the command itself as conditional for the while construct.

while ! ./fetch_remote_work.sh; do :; done

  • Great! but this works while [ ./fetch_remote_work.sh ]; do; done, please update your answer – smarber Nov 22 '17 at 13:28
  • 2
    @smarber While Spidey's answer is semantically correct (although probably should be while !), your comment is not. [ x ] just checks that the string x is not empty, so your script is never run at all. – Chris Down Nov 22 '17 at 13:29
  • @ChrisDown while ! works but while ./fetch... doesn't. However while [ ./fetch_remote_work.sh ] works too. To reproduce what I'm saying, you can create fetch_remote_work.sh with exit 2 inside... – smarber Nov 22 '17 at 13:36
  • 1
    -bash: syntax error near unexpected token ';' -- you need some sort of command after your do, like a sleep or : – Jeff Schaller Nov 22 '17 at 13:43
  • @JeffSchaller you're right! – smarber Nov 22 '17 at 13:45

If you want to run something until it has a zero return code,

until [ $RANDOM -eq 42 ]
  echo looking for the answer to life, the universe, and everything

(or as a one-liner)

until [ $RANDOM -eq 42 ]; do echo looking for the answer to life, the universe, and everything; done

For your example:

until ./fetch_remote_work.sh; do :; done

This loop does "nothing" (execute the : builtin) until the fetch_remote_work.sh script returns 0.

  • Oh boy! New useful thing, I never heard of before, to learn : again .... thx! – smarber Nov 22 '17 at 13:44

Change the first line to false, forcing the desirable condition for the first iteration.

  • It's makes it better, indeed. However it's not as perfect as do while – smarber Nov 22 '17 at 13:21
  • 1
    I'm thinking the actual question is "is there an equivalent to do-while in shell script?" – Spidey Nov 22 '17 at 13:24
  • Maybe you're right, but if there is another way without even using a loop I'll take it – smarber Nov 22 '17 at 13:26
  • I don't understand why you're looking for a way "without a loop" when your question says "I need to run it many times until it works" – Jeff Schaller Nov 22 '17 at 13:33
  • @JeffSchaller no, I'm just looking for a cleaner way than what I did, with or without loop, I don't care, that's why I don't talk about the technique in the title – smarber Nov 22 '17 at 13:38

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.