Bao Haojun
Bao Haojun

Reputation: 1006

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

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?

Upvotes: 5

Views: 1033

Answers (1)

Paul Hodges
Paul Hodges

Reputation: 15418

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.

Upvotes: 1

Related Questions