【问题标题】:While loop and set [duplicate]While循环并设置[重复]
【发布时间】:2021-11-09 14:38:55
【问题描述】:

我在 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
  • 有没有更好的运行((x++))的方法?
  • 你可以使用((++x))
  • @Saraha :当您的某些命令进行整数运算时,使用 set -e 有什么意义?我看不出你的程序-e 的哪个位置有意义。 pipefail 也一样。在你的情况下,只有 set -u 对我有意义。

标签: bash while-loop


【解决方案1】:

((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 set -e。

【讨论】:

猜你喜欢
  • 2014-03-23
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 2019-04-13
  • 2014-08-29
  • 2011-11-23
相关资源
最近更新 更多