Here document: no parameter expansion

2019-08-09 05:52发布

问题:

Is there any way to turn off parameter expansion in here document?

Shell command:

$ cat > analyze.sh <<EOF    
awk -F: '{print $NF}' asr.log | sort > tmp  
awk -F '(' '{print $NF}' asr.log | awk '{print $1}' |  sort > tmp2
EOF

I got this in analyze.sh:

awk -F: '{print }' asr.log | sort > tmp
awk -F '(' '{print }' asr.log | awk '{print }' |  sort > tmp2

回答1:

You need to quote the delimiter:

$ cat > analyze.sh <<"EOF"    
awk -F: '{print $NF}' asr.log | sort > tmp  
awk -F '(' '{print $NF}' asr.log | awk '{print $1}' |  sort > tmp2
EOF

This prevents the shell from expanding the here-document:

$ cat analyze.sh 
awk -F: '{print $NF}' asr.log | sort > tmp  
awk -F '(' '{print $NF}' asr.log | awk '{print $1}' |  sort > tmp2

Documentation

This is documented in man bash:

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 `. [Emphasis added]



回答2:

You can quote the EOF to disable expansion:

cat > analyze.sh <<'EOF'
awk -F: '{print $NF}' asr.log | sort > tmp  
awk -F '(' '{print $NF}' asr.log | awk '{print $1}' |  sort > tmp2
EOF


标签: linux bash shell