bash - shell 中的 <<EOF 和 <<\EOF heredocs 有什么区别

标签 bash shell sh

我注意到它们之间的几个区别:

<<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/

相关文章:

linux - 在 Linux 上,如何使用 POSIX shell 禁用鼠标一秒钟,而不是等待第二个并立即做一些工作?

perl - 在后台执行,但限制执行次数

Bash 子外壳/管道 - 哪些部分在子外壳中执行?

linux - shell脚本终止程序但不终止脚本本身

bash - 是否可以列出与 ls 模式匹配的文件?

linux - 在shell脚本中执行sql

regex - 如何在触发 "unterminated substitute pattern"错误的 bash 脚本中重新组织 sed 正则表达式中的嵌套引号?

bash - 如果连接中断,ffmpeg 从实时流中录制视频将关闭

shell - tmux 打开终端失败 : not a terminal

linux - 我收到错误语法错误:”(“意外”