How to suppress variable substitution in bash heredocs

前端 未结 2 370
遇见更好的自我
遇见更好的自我 2020-12-03 22:46

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 va         


        
相关标签:
2条回答
  • 2020-12-03 23:04

    Put backlash before the $ sign

    $ VAR=XXX
    $ cat << END
    > dk
    > \$VAR
    > END
    dk
    $VAR
    
    0 讨论(0)
  • 2020-12-03 23:12

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

    0 讨论(0)
提交回复
热议问题