0

Can somebody help me with this... I can't seem to get a working while statement (it never enters the loop)... Tried many different syntaxes and I'm stuck.

tries=0
success=false

while (!${success} && ${tries} -lt 10); do
  {
    echo "Trying..." &&
    myCommand &&
    success=true &&
    echo "Success"
  } || {
    success=false &&
    echo "Failed"
  }
  let tries=tries+1
done

2 Answers 2

2

Just a little change

tries=0
success=false

while (( !${success} && ${tries} < 10 )); do
  {
    echo "Trying..." &&
    myCommand &&
    success=true &&
    echo "Success"
  } || {
    success=false &&
    echo "Failed"
  }
  let tries=tries+1
done

Difference in Bash between IF statements with parenthesis and square brackets

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, that got me a little bit further. Thank you... However, there seems to be something wrong with my success=true variable assignment. The loop doesn't exit on that condition, it executes 10 times whether the command succeeds or not. Any idea?
Trivially, success=0 and while (( ${success} < 1 && ${tries} < 10 )); do ... shoud work
2

You appear to be trying to write C code in bash. Specifically, your use of success as both a Boolean flag and an executable program is a bit awkward. Try

while (( tries < 10 )); do
    { myCommand && echo Success && break; } || { echo Failed && let tries=tries+1; }
done

Using an explicit if statement would also be more readable:

while (( tries < 10 )); do
    if myCommand; then
        echo Success
        break
    else
        echo Failed
        let tries=tries+1
    fi
done

Comments

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.