阅读高级Bash脚本指南
Chapter 19. Here Documents。
这里有一个例子,它将内容写到/ tmp / yourfile这里的文件
cat << EOF > /tmp/yourfilehere
These contents will be written to the file.
This line is indented.
EOF
注意,最后的’EOF'(LimitString)在单词前面不应该有任何空格,因为这意味着LimitString不会被识别。
在shell脚本中,您可能希望使用缩进来使代码可读,但是这可能会产生在您的here文档中缩进文本的不良效果。在这种情况下,使用<< – (后跟一个破折号)来禁用前导选项卡(请注意,为了测试这一点,您需要使用制表符字符替换前导空格,因为我无法在此打印实际的制表符。)
#!/usr/bin/env bash
if true ; then
cat < /tmp/yourfilehere
The leading tab is ignored.
EOF
fi
如果您不想解释文本中的变量,请使用单引号:
cat << 'EOF' > /tmp/yourfilehere
The variable $FOO will not be interpreted.
EOF
通过命令管道管道heredoc:
cat <
foo
bar
baz
EOF
输出:
foo
bbr
bbz
…或使用sudo将heredoc写入文件:
cat <
foo
bar
baz
EOF