你只需要做一个很小的改动;在这个here-document的分界符后面加上单引号。
cat <<'EOF' >> brightup.sh
或者等价地反斜杠转义它:
cat <<\EOF >>brightup.sh
不引用的话,这个文档会进行变量替换,反引号会被评估等等,就像你发现的那样。
如果你需要扩展一些值,但不是全部,你需要逐个转义你想要防止的值。
cat <<EOF >>brightup.sh
#!/bin/sh
# Created on $(date # : <<-- this will be evaluated before cat;)
echo "\$HOME will not be evaluated because it is backslash-escaped"
EOF
将会产生
#!/bin/sh
echo "$HOME will not be evaluated because it is backslash-escaped"
根据 @fedorqui 的建议,这里是来自 man bash 的相关部分:
Here Documents
This type of redirection instructs the shell to read input from the
current source until a line containing only delimiter (with no
trailing blanks) is seen. All of the lines read up to that point are
then used as the standard input for a command.
The format of here-documents is:
<<[-]word
here-document
delimiter
No parameter 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. In the
latter case, the character sequence \<newline>
is ignored, and \
must be used to quote the characters \
, $
, and `
.
对于一个相关的问题,还可以参考
https://dev59.com/iG445IYBdhLWcg3wTIZf#54434993。
$(command)
而不是\
command`。要获取文件的内容,Bash有
$(<file)`。 - tripleee