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)?

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
4
  • Thanks. How about the same questions for the other syntax of for-loop? – Tim Apr 24 '16 at 15:52
  • @Tim see update – muru Apr 24 '16 at 16:00
  • what does _ mean in bash -c 'for i; do echo $i; break; done' _ a b c? – Tim Apr 24 '16 at 16:05
  • _ is $0 in this case. Since for i only loops from the first argument, I used _ as placeholder. unix.stackexchange.com/q/152391/70524 – muru Apr 24 '16 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.