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.

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
Thanks for the explanation, I've tried it again using your edit @chepner and it runs without the syntax error as well now.
0

You can use for loop:

for ((count=0; i<20 && $(MyFunction $arg1 $arg2) == 1; count++)); do
   echo $count
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.