How to suppress variable substitution in bash heredocs

左心房为你撑大大i 提交于 2019-12-28 06:58:19

问题


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.


回答1:


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




回答2:


Put backlash before the $ sign

$ VAR=XXX
$ cat << END
> dk
> \$VAR
> END
dk
$VAR


来源:https://stackoverflow.com/questions/31645341/how-to-suppress-variable-substitution-in-bash-heredocs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!