Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress variable substitution in bash heredocs

Is it possible to create a heredoc that does not become subject to variable expansion?

e.g.

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

Update I am aware of escaping by \. My actual heredoc has many variables in it - and it is error prone and tedious to escape all of them.

like image 397
WestCoastProjects Avatar asked Jul 27 '15 05:07

WestCoastProjects


1 Answers

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.]

like image 144
John1024 Avatar answered Nov 10 '22 02:11

John1024