Shell – How to end a here-document that starts with <<\\$fff

here-documentshell

I was asked the following question in a test on shell scripting at my university, which never gave an answer, and google is of little help.

Q: What is the line separator that should be used to end this here-document?

fff=file
xyz <<\\$fff
...

Best Answer

The line which ends the here document is

\$fff

From the man bash section on Here Documents:

The format of here-documents is:

          <<[-]word
                  here-document
          delimiter

No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \newline is ignored, and \ must be used to quote the characters \, $, and `.

word does undergo quote removal, so \\$fff is dequoted to \$fff. But, as the manpage says, no variable expansion is done so it stays that way.

The body of a here document might or might not undergo variable expansion and backslash interpretation. In this case, since word contains a quoted character (that is, the backslash), parameter expansion and backslash dequoting are not performed on the text of the here document.

However, the input is compared with the terminating sequence before variable expansion, so it is not necessary to backslash-escape the \ nor the $ in the terminating line.

Related Question