While loop and set



我在bash中有以下while循环:

set -euo pipefail
x=0
rounds=10
while [ $x -le $rounds ]
do
y=$(($x+1))
echo $x
echo $y
((x++))
done

但是它在一次迭代后停止:

$ bash test.sh
0
1

只有当我移除set -euo pipefail时,我的循环才能完全通过。为什么呢?

((x++))失败。set -e指示bash在任何命令失败时退出。不要使用set -e

来自bash手册页:

((expression))
The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION.  If the value of the expression is non-zero, the
return status is 0; otherwise the return status is 1.  This is exactly equivalent to let "expression".

你可能应该只执行echo $((x++))来增加x,或者执行((x++)) || true: $((x++)),或者(最合理的)停止使用set -e

可以使用((++x)),但我认为这是一个坏主意,因为它隐藏了问题,而不是解决它。如果你有一个从x <你会突然遇到一个非常意想不到的bug。真的,正确的做法是停止使用set -e。>

最新更新