首页 > 解决方案 > 在具有多个条件的bash中编写do while循环

问题描述

我在使用多个条件的 bash 中编写 do-while 循环时遇到了一些麻烦。

我的代码目前可以这样工作:

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

但我想在“do-while”循环中添加第二个条件,如下所示:

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

当我这样做时,我得到一个“找不到命令错误”。

我一直在尝试这篇文章中的一些 while 循环示例,但没有运气,我使用的 do-while 示例来自这里。特别是有 137 个赞的答案。

标签: bashdo-while

解决方案


(是语法的一部分,$count不是有效的命令。testor[是用于“测试”表达式的有效命令。

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

您提到的答案使用算术表达式 with (((不是 single (,而是 double((之间没有任何东西)。你也可以这样做:

while
   count=$((count+1))
   (( "$(MyFunction "$arg1" "$arg2")" == 1 || count < 20 ))
do
   :
done

推荐阅读