1

In Bash,

  1. the syntax of the C-like for-loop is:

    for (( expr1 ; expr2 ; expr3 )) ; do commands ; done
    

    Can the execution of commands affect the evaluations of the three arithmetic expressions expr1, expr2, and/or expr3, and therefore change the iterations (e.g. the number of iterations)?

    Or are the iterations (e.g. the number of iterations) unaffected by execution of commands in each iteration?

  2. The other syntax of the for command is:

    for name [ [in [words ...] ] ; ] do commands; done
    

    Can execution of commands in each iteration affect the iterations (e.g. the number of iterations)?

Tim
  • 101,790

1 Answers1

3

Sure:

$ bash -c 'for ((i=0;i<10;i++)); do echo $i; ((i++)); done'
0
2
4
6
8

In the for ((expr1; expr2; expr3) form, expr2 (and expr3, if expr2 didn't fail) are evaluated each time the loop is run. With the other form, bash starts the loop after words have been expanded (that includes performing command substitution, globbing, etc.). So you can't affect the possible values of the iteration variable (name) once the loop starts. You can, of course:

$ bash -c 'for i; do echo $i; break; done' _ a b c
a
muru
  • 72,889