0

I'm having some trouble writing a do-while loop in bash with multiple conditions.

My code currently works when it is like this:

    while
    count=$((count+1))
    ( MyFunction $arg1 $arg2 -eq 1 )
    do
       :
    done

But I want to add a second condition to the "do-while" loop like so:

    while
    count=$((count+1))
    ( MyFunction $arg1 $arg2 -eq 1 ) || ( $count -lt 20 )
    do
       :
    done

When I do this I get an "command not found error".

I've been trying some of the while loop examples from this post but had no luck and the do-while example I use is from here. In particular the answer with 137 likes.

Bobybobp
  • 95
  • 9

2 Answers2

2

The ( is part of syntax and $count is not a valid command. The test or [ is a valid command that is used to "test" expressions.

while
   count=$((count+1))
   [ "$(MyFunction "$arg1" "$arg2")" -eq 1 ] || [ "$count" -lt 20 ]
do
   :
done

The answer you mention uses arithmetic expressions with (( (not a single (, but double (( without anything between). You could also do:

while
   count=$((count+1))
   (( "$(MyFunction "$arg1" "$arg2")" == 1 || count < 20 ))
do
   :
done
chepner
  • 497,756
  • 71
  • 530
  • 681
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • I understand why this should work for me but I don't understand why I get a syntax error while using it. I get an error like: -eq 1 || count < 20 : syntax error in expression. It then mentions the error token being in my function, but it looks like the code runs through to completion. – Bobybobp Oct 07 '19 at 12:17
  • 1
    Since `bash` is interpreted, parsing and evaluation/execution run somewhat in parallel. A syntax error becomes just another run-time error, and is interpreted as a failure, the same as if a command actually ran but had a non-zero exit status. – chepner Oct 07 '19 at 12:49
  • Thanks for the explanation, I've tried it again using your edit @chepner and it runs without the syntax error as well now. – Bobybobp Oct 07 '19 at 12:54
0

You can use for loop:

for ((count=0; i<20 && $(MyFunction $arg1 $arg2) == 1; count++)); do
   echo $count
done
anubhava
  • 761,203
  • 64
  • 569
  • 643