How to suppress variable substitution in bash heredocs

Quote the delimiter:

cat <<-"EOF"  > somefile.sh
Do not print current value of $1 instead evaluate it later.
EOF

This results in:

$ cat somefile.sh 
Do not print current value of $1 instead evaluate it later.

Documentation

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
\ is ignored, and \ must be used to quote the characters \,
$, and `.

If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing
delimiter. This allows here-documents within shell scripts to be
indented in a natural fashion. [Emphasis added.]

Leave a Comment