I have the following:
#!/bin/bash a=0 for d in ./*/ ; do ( cd "$d" ((a++)) echo $a ); done Which goes into each directory in my path, increments a and prints a. However, the output is always 1. Why is that?
From bash(1):
(list) list is executed in a subshell environment (see COMMAND EXECU‐ TION ENVIRONMENT below). Variable assignments and builtin com‐ mands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list.
#!/bin/bash a=0 for d in ./*/ do ((a++)) echo $a done (also slightly more conventionally formatted)
the result is:
1 2 3 4 5 6 7 for d in `seq 1 3`;do echo $d ;done to not pollute the interactive shell and without $a which is not needed. If needed: a=0;for d in `seq 1 3`;do echo $a ;((a++));done Because you put the loop body in unnecessary ()'s which makes it execute in a subshell if I recall correctly.