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
ddx001
  • 2,575
  • 1
  • 17
  • 13

2 Answers2

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

Community
  • 1
  • 1
Raul Andres
  • 3,766
  • 15
  • 24
  • 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? – ddx001 Jan 14 '14 at 12:52
  • Trivially, `success=0` and `while (( ${success} < 1 && ${tries} < 10 ));` do ... shoud work – Raul Andres Jan 14 '14 at 13:03
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
chepner
  • 497,756
  • 71
  • 530
  • 681