Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a newline inside a heredoc inside a command substitution lost by bash (but not dash)?

Tags:

bash

When run in bash, this command:

cat <<EOF
hello \\
world
EOF

will output as I expect:

hello \
world

But this one outputs hello \world (without the newline), and is unexpected:

echo "$(cat <<EOF
hello \\
world
EOF
)"

If I run the second command with dash, then the output is as expected (with a newline).

Why is the newline removed in 2nd command in bash?

like image 662
Bao Haojun Avatar asked Nov 06 '22 00:11

Bao Haojun


1 Answers

Because you are re-parsing the output again, so the double-backslash has already been parsed, and the now-single backslash is quoting the newline, making it a continuation line.

Take them both out and it works as you'd expect.


EDIT

See comments below.
I'd delete the answer, but the useful comments would go as well.

like image 53
Paul Hodges Avatar answered Nov 11 '22 07:11

Paul Hodges