while循环和设置

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 < 0 开始的 运行 的循环,你会突然遇到一个非常意想不到的错误。真的,正确的做法是停止使用 set -e.