简体   繁体   中英

Writing a do while loop in bash with multiple conditions

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.

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

You can use for loop:

for ((count=0; i<20 && $(MyFunction $arg1 $arg2) == 1; count++)); do
   echo $count
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM