Search code examples
bashshellbackslash

Bash herefile with backslash different result on ubuntu 18.04 and 20.04?


I want to put a longer text into a shellscript variable and used herefile and backslash like in the following example. I see different behaviour with ubuntu 18.04 and ubuntu 20.04 (both use /bin/bash, utf-8:

param="$(cat <<'EOF'
a\
b
EOF
)"
echo $param > ./testfile.txt

output (cat ./testfile.txt) on ubuntu 18.04:

ab

output on ubuntu 20.04:

a\ b

Why is the output different?

PS: using EOF instead of 'EOF' the output is with both versions:

ab

Solution

  • This is a bug fix in version 5.0:

    kk. Fixed a bug that caused bash to remove backslash-newline pairs from the body of a here-document with a quoted delimiter inside a command substitution.

    In 4.4, it was removed, so that cat saw a and b immediately adjacent in its input. Now, they are preserved, but the backslash is a literal character in the value of param, and the following newline is discarded during word-splitting, so the words a\ and b are output by echo separated by a single space.

    If you quote $param, you'll see the newline.

    $ echo "$param"
    a\
    b