1

I have the following while loop in bash:

set -euo pipefail
x=0
rounds=10

while [ $x -le $rounds ]
do
    y=$(($x+1))
    echo $x
    echo $y
    ((x++))
done

But it stops after one iteration:

$ bash test.sh
0
1

Only when I remove set -euo pipefail, my loops run through completely. Why is that?

Saraha
  • 144
  • 1
  • 12

1 Answers1

1

((x++)) fails. set -e tells bash to exit if any command fails. Don't use set -e.

From the bash man page:

   ((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".

You should probably just do either echo $((x++)) to increment x, or do ((x++)) || true, or : $((x++)), or (most reasonable) stop using set -e.

You could use ((++x)), but I think that's a bad idea, since it hides the problem instead of fixing it. If you ever had a loop that was running from x < 0, you would suddenly encounter a very unexpected bug. Really, the right thing to do is to stop using set -e.

William Pursell
  • 204,365
  • 48
  • 270
  • 300