while 循环不检查 shell 中的条件

while 循环不检查 shell 中的条件

我正在尝试使用 shell 的指数退避算法。但是当我将挂起的参数作为参数传递时,它会运行永无休止的循环吗?

#!/bin/bash
MAX_RETRIES=5
retries=0
status=$1
while [ $retries -le  $MAX_RETRIES ];
#while
     echo  $retries
        retries=$(( $retries + 1 ))
do
sleep $(( 1^$retries* 1))
        if [[ "$status" == "success" ]]; then
        echo "success"
        break;
        elif [[ "$status" == "pending" ]]; then
        echo "pending"
        else
        echo "I am else."
        fi
        echo "Retries in do $retries"
echo "after do"; done

任何想法?

答案1

跳出循环的唯一方法是 for $statusto be success。这是因为在循环头中赋值的结果将是真值并且循环将是无限的。

你的循环:

while [ some test ]; echo 'something'; retries=$(( $retries + 1 )); do
    loop body
done

相反,将echoand 赋值移动到循环中:

#!/bin/bash

MAX_RETRIES=5
retries=0
status="$1"

while [ "$retries" -le "$MAX_RETRIES" ]; do
    echo "$retries"
    retries=$(( retries + 1 ))
    sleep $(( 1^retries * 1))

    if [[ "$status" == "success" ]]; then
        echo "success"
        break;
    elif [[ "$status" == "pending" ]]; then
        echo "pending"
    else
        echo "I am else."
    fi

    echo "Retries in do $retries"
done

echo "done."

或者,与case .. esac

#!/bin/bash

MAX_RETRIES=5
retries=0
status="$1"

while [ "$retries" -le "$MAX_RETRIES" ]; do
    echo "$retries"
    retries=$(( retries + 1 ))
    sleep $(( 1^retries * 1))

    case "$status" in
        success)
            echo "success"
            break ;;
        pending)
            echo "pending" ;;
    esac

    echo "Retries in do $retries"
done

echo "done."

答案2

sleep $(( 1^$retries * 1))

这可能不会达到您想要的效果。^是按位异或,所以你会得到嗯,嗯,1,0,3,2,等等...求幂是**。当然,也是1**Xjust 1,并且X*1is just X,但您可能打算稍后修复常量。

相关内容