Here document: no parameter expansion

2019-08-09 05:37发布

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

标签: linux bash shell
2条回答
在下西门庆
2楼-- · 2019-08-09 06:12

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]

查看更多
来,给爷笑一个
3楼-- · 2019-08-09 06:28

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
查看更多
登录 后发表回答