$ declare -i i=0
$ for j in {0..2}; do echo "${j} $((i++))"; done
0 0
1 1
2 2
$ for j in {0..2}; do echo "$(echo "${j} $((i++))")"; done
0 3
1 3
2 3
$
Why i
doesn't get incremented in the 2nd for loop?
(Yes, I know that there's a workaround.)
$ declare -i i=0
$ for j in {0..2}; do echo "${j} $((i++))"; done
0 0
1 1
2 2
$ for j in {0..2}; do echo "$(echo "${j} $((i++))")"; done
0 3
1 3
2 3
$
Why i
doesn't get incremented in the 2nd for loop?
(Yes, I know that there's a workaround.)
It gets incremented in the subshell created by the
$(command substitution)
. When that process exits, the modified value is lost.Here are similar ways of seeing the same effect: