![while 循环不检查 shell 中的条件](https://linux22.com/image/113580/while%20%E5%BE%AA%E7%8E%AF%E4%B8%8D%E6%A3%80%E6%9F%A5%20shell%20%E4%B8%AD%E7%9A%84%E6%9D%A1%E4%BB%B6.png)
我正在尝试使用 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 $status
to be success
。这是因为在循环头中赋值的结果将是真值并且循环将是无限的。
你的循环:
while [ some test ]; echo 'something'; retries=$(( $retries + 1 )); do
loop body
done
相反,将echo
and 赋值移动到循环中:
#!/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**X
just 1
,并且X*1
is just X
,但您可能打算稍后修复常量。