Shell – echo result from subshell in zsh

echosubshellzsh

In zsh, the following 2 commands results differently:

a=$(</etc/hosts) && echo $a
echo $(</etc/hosts)

The 1st prints contents line by line, while the 2nd prints contents as a whole in one single line.

I guess it is because the subshell returns result line by line to the main echo process, but I can not confirm that.

Someone can help me to clear that?

Best Answer

In zsh, unquoted variables are not automatically split and glob, while unquoted command substitution will be split into words using values in IFS.

In your case, the first command saved content of file /etc/hosts to variable a, echo $a prints value of a variable without split and glob, you get the contents of /etc/hosts (split and glob are not performed in RHS of variable assignment).

echo $(</etc/hosts) used unquoted command substitution, the result will be split into words, so you get content of /etc/hosts as all words delimited by space.

Related Question