作为此处较早答案的后期推论,您可能最终会遇到希望对一些但不是所有变量进行插值的情况。您可以通过使用反斜杠来转义美元符号和反引号来解决这个问题;或者您可以将静态文本放入变量中。
Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE
演示:https ://ideone.com/rMF2XA
请注意,任何引用机制——\____HERE
或"____HERE"
或'____HERE'
——都将禁用所有变量插值,并将此处的文档转换为一段文字文本。
一个常见的任务是将局部变量与脚本结合起来,脚本应该由不同的 shell、编程语言或远程主机进行评估。
local=$(uname)
ssh -t remote <<:
echo "$local is the value from the host which ran the ssh command"
# Prevent here doc from expanding locally; remote won't see backslash
remote=\$(uname)
# Same here
echo "\$remote is the value from the host we ssh:ed to"
: