0

So I have this If statement that checks what the exit code of the script is:

if [ $? -eq 0 ]; then
    wasSuccessful=true;
fi

In other languages, I would do something like:

while wasSuccessful == false

And then the loop would keep running until the exit code was true. (I plan to implement a loop counter as well for too many failed attempts, but that's a different problem to solve)

I think I need a here-string, but I'm not exactly sure how that would look. Here's a rough outline of my code right now, in Bash:

wasSuccessful=false

while [ "$wasSuccessful" = "false" ]
do

#Bunch of code here, then the check for exit code

if [ $? -eq 0 ]; then
    wasSuccessful=true;
fi

done

Any suggestions on how to do something like this would be much appreciated :)

5
  • Your code seems OK. What is the problem you are facing? All variables in Bash are global unless declared as local inside a function. Commented Jun 13, 2017 at 23:47
  • I thought the while loop executed in a subshell, so changes I make to variables are saved only to that session scope. Is that not correct? Commented Jun 13, 2017 at 23:54
  • @iMatthewCM the while loop not executed in subshell, unless you put them inside quote (commands). Commented Jun 13, 2017 at 23:55
  • The confusion is probably that often people will pipe input into a while loop, and things involved in a pipeline are run in subshells. So if you did, say, getent passwd user_prefix | while read -r ent; do... then that loop would be in a subshell, as written yours would not create a subshell Commented Jun 14, 2017 at 0:23
  • Oh, that's very helpful, thank you @EricRenouf Commented Jun 14, 2017 at 16:17

1 Answer 1

2

The question is how to exit while loop when the latest command execute successfully inside while loop?

You don't need a global variable to check. Just check the status of previous command and break it if succeed.

while true
do
    # a bunch of code here
    [ $? -eq 0 ] && break
done
Sign up to request clarification or add additional context in comments.

3 Comments

The opposite of that I think. If the exit code is anything other than 0, I need to keep looping.
Yes, the code above will keep your loop running if the exit code is not 0.
Well...that's pretty awesome. Thank you very much! That's much more elegant than what I was doing. I'll give that a shot when I get back to work tomorrow (just leaving now) and if it works I'll accept the answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.