在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时,循环才会完全运行。为什么会这样呢?
发布于 2021-09-14 11:58:55
((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。
https://stackoverflow.com/questions/69177319
复制相似问题