我注意到它们之间的几个区别:
在 <<EOF
里面heredoc,不能给变量赋新值:
bash <<EOF
s=fds
echo $s
EOF
将打印空行,其中
bash <<\EOF
s=fds
echo $s
EOF
将打印变量的值 s
.
全局变量可以在<<EOF
内访问但不在 <<\EOF
内(使用 export
可以访问 <<\EOF
中的变量):
s=fds
bash <<EOF
echo $s
EOF
将打印值 fds
,在哪里,
s=fds
bash <<\EOF
echo $s
EOF
将打印空行。
那么它们之间有什么区别,合法的记录行为是什么?
最佳答案
来自POSIX spec :
If any character in word is quoted, the delimiter shall be formed by performing quote removal on word, and the here-document lines shall not be expanded. Otherwise, the delimiter shall be the word itself.
所以 <<EOF
版本有 shell 在运行此处文档内容和 <<\EOF
之前 展开所有变量(或 <<'EOF'
或 <<EO'F'
等)版本不扩展内容(这让 bash
在这种情况下完成这项工作)。
尝试使用 cat
而不是 bash
以便更清楚地了解正在发生的事情。
还有 printf '[%s]\n' "$s"
和/或可能bash -x
而不是 bash
:
$ bash -x <<EOF
s=fds
printf '[%s]\n' "$s"
EOF
+ s=fds
+ printf '[%s]\n' ''
[]
$ bash -x <<\EOF
s=fds
printf '[%s]\n' "$s"
EOF
+ s=fds
+ printf '[%s]\n' fds
[fds]
关于bash - shell 中的 <<EOF 和 <<\EOF heredocs 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31679384/