$ 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:
i=0
bash -c 'let i++' # Subprocess
( let i++ ) # Explicit subshell
let i++ & wait # Backgrounded process
: <( let i++ ) # Process substitution
let i++ | cat # Pipeline
echo "$i" # Still 0