在 while 循环中使用 here 文档变量

vde*_*nne 0 bash here-document

我在循环中使用 Here Document 变量时遇到问题。因为这有效

while IFS= read -r line; do
  echo "(${line})"
done <<EOF
one
two
three
EOF
Run Code Online (Sandbox Code Playgroud)

但这不

foo=<<EOF
one
two
three
EOF

while IFS= read -r line; do
  echo "(${line})"
done <<<"$foo"
Run Code Online (Sandbox Code Playgroud)

现在我在 bash 脚本方面有点菜鸟。除了我头上有问号之外,我想知道如何保留第二种语法(脚本顶部的 here 文档)并仍然使其以某种方式工作。

谢谢你的帮助。

mur*_*uru 6

这不会将变量设置foo为 heredoc 的内容:

foo=<<EOF
one
two
three
EOF
Run Code Online (Sandbox Code Playgroud)

这是对空字符串的变量赋值,带有重定向。这可能会使发生的事情更清楚:

foo=""  <<EOF
one
two
three
EOF
Run Code Online (Sandbox Code Playgroud)

但是你真的不需要heredocs。做就是了:

foo="one
two
three"
Run Code Online (Sandbox Code Playgroud)