The GNU bash documentation clearly explains this behavior under Command Substitution
If the substitution appears within double quotes, word splitting and filename expansion are not performed on the results.
Since the second case has a a unquoted substitution, the resultant string fooXbarXbaz
is subjected to word splitting by the shell by the value of IFS
set, which splits the word into multiple words.
In the first case for x in fooXbarXbaz;
, the string is subjected to pathname expansion (aka glob expansion). The shell performs this at a stage much later than word-splitting, after finishing all possible expansions (see Shell Expansions), so the resultant string is treated literally.
To add further take the case of variable expansion $var
, which happens before pathname expansion, undergoes same process like your OP
IFS='X'; var=fooXbarXbaz; for x in $var; do echo Y${x}Z; done
An unquoted variable expansion like command substitution undergoes word splitting by the value of IFS
. That's why generally we insist on quoting all expansions to avoid unforseen word splitting done by the shell.
IFS='X'; vars=fooXbarXbaz; for x in $vars; do echo Y${x}Z; done