简体   繁体   English

在具有多个条件的 bash 中编写一个 do while 循环

[英]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.我在 bash 中使用多个条件编写 do-while 循环时遇到了一些麻烦。

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:但我想在“do-while”循环中添加第二个条件,如下所示:

    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 .我一直在尝试这篇文章中的一些 while 循环示例,但没有运气,我使用的 do-while 示例来自这里 In particular the answer with 137 likes.特别是有 137 个赞的答案。

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. (是语法的一部分, $count不是有效命令。 test[是用于“测试”表达式的有效命令。

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循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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