Hi all,
the bash reference manual states in chapter 3.5.7: The shell scans
the results of parameter expansion, command substitution, and
arithmetic expansion that did not occur within double quotes for word
splitting.. I thought I had understood this, but then came across a
problem.
Let's look at a very simple script:
echo 'line1' file
echo 'line2' file
echo $(cat file)
When you run this script, you get the following output:
line1 line2
This is like expected: The output of cat file contains at least one
embedded newline; since the command substitution does not take place
within double quotes, the newline is replaced by a space when the
result of the expansion is word-splitted.
The script
echo 'line1' file
echo 'line2' file
echo $(cat file)
gives the output
line1
line2
which is also the expected one because now the word splitting does not
occur after the command substitution because of the double
quotes;thus, the newline is conserved and the output is two lines.
So far, so good. The problem comes up if I am working with variables
that store the result of the command substitution.
The script
echo 'line1' file
echo 'line2' file
RESULT=$(cat file)
echo $RESULT
gives the following output:
line1
line2
I don't understand why: the command substitution $(cat file) is not
within double quotes, so word splitting should be applied to the
result of the substitution and any embedded newlines should be
removed. Thus, $RESULT should contain text without newlines after line
three in the above script is executed.
But obviously, the original output of $(cat file), including embedded
newlines, has made it into $RESULT. Otherwise, the output would be
just one line and not two.
So why does this happen? I would be grateful if someone could explain
when the word splitting is exactly taking place.
Thank you very much,
Peter