Search code examples
bashheredoc

Heredoc with backslash


What is the difference between

cat >test.txt <<\EOF
hello
world
EOF

and

cat >test2.txt << EOF
hello
world
EOF

I'm writing a ANTLR based syntax coloring and the \ after the << irritates me (found in an example file). What does it mean? Can I ignore it for syntax coloring like a -?


Solution

  • From the POSIX standard on here-document syntax:

    If any part of word [the thing after << - GD] is quoted, the delimiter shall be formed by performing quote removal on word, and the here-document lines shall not be expanded. Otherwise, the delimiter shall be the word itself.

    So... do you color shell expansions inside here-documents? That is, in something like this:

    cat >test2.txt << EOF
    hello $somevar
    world $(somecommand)
    EOF
    

    Do you color $somevar and $(somecommand) as variable and command expansions respectively? If so, you need to disable that if the delimiter word is quoted or escaped.