7

I came across the following syntax in a here document not mentioned in bash’s man page

cat <<\EOF
hello world
EOF

The man page only mentions quotes around the delimiter and a - in front of it. So what does it mean?

karlsebal
  • 795
  • 8
  • 20
  • 2
    [Bash's man page](https://manpages.debian.org/stretch/bash/bash.1.en.html) says "if _any part_ of 'word' is quoted...", so it's not just about quotes around the terminator word. And for the purposes here, the backslash is a quoting operator, it's listed as such under the QUOTING section: "There are three quoting mechanisms: the escape character, single quotes, and double quotes. [...] A non-quoted backslash (\) is the escape character.". (One could argue the C-quotes `$'...'` should count as a fourth mechanism, but for whatever reason they're not included in that count.) – ilkkachu Sep 30 '21 at 13:19
  • I clarified that on the relevant part of [What are the shell's control and redirection operators?](https://unix.stackexchange.com/q/159513/170373), but I'm not sure I want to close this as a duplicate just like that. – ilkkachu Sep 30 '21 at 13:20
  • oh, thank you for clarifying »quoting«! I only was thinking of double or single quotes. I should update the answer accordingly – karlsebal Sep 30 '21 at 13:31

1 Answers1

20

In fact the man page is thorough about this since it reads

If any part of word is quoted

where »quoting« can be any operator of ', " or \. \EOF quotes E and serves the same purpose as quoting WORD entirely thus preventing parameter expansion in the here document.

a="something"
cat <<\EOF
$a
EOF

and

a="something"
cat <<"EOF"
$a
EOF

both will result in

$a

rather than

something

as would be the case with

cat <<EOF
$a
EOF

In fact, since »any part of WORD « can be quoted you may even use <<E\OF, <<E"O"F or <<EOF""

karlsebal
  • 795
  • 8
  • 20
  • 5
    Note that it's quoting any part of the delimiter that triggers that behaviour. Quoting operators include backslash, `'...'`, `"..."` (also `$'...'` / `$"..."` in some shells). So any of `cat << \EOF` (only `E` is quoted), `cat << E\OF`, same as `cat << E'O'F`, even `cat << EOF''` will do. Personally, I tend to use `cat << 'EOF'` where the entirety of `EOF` is quoted, same as `cat << \E\O\F` – Stéphane Chazelas Sep 30 '21 at 12:57
  • thank you, Stéphane, I updated the answer accordingly – karlsebal Sep 30 '21 at 13:42
  • 3
    Wait, does double-quoted `"EOF"` also suppress variable expansion? That's slightly unexpected. – u1686_grawity Oct 01 '21 at 05:07
  • Yes, it does :) – karlsebal Oct 01 '21 at 06:50