Read the Advanced Bash-Scripting Guide Chapter 19. Here Documents .
(阅读《高级Bash脚本指南》 第19章 。)
Here's an example which will write the contents to a file at /tmp/yourfilehere
(这是一个将内容写入/tmp/yourfilehere
此处的示例)
cat << EOF > /tmp/yourfilehere
These contents will be written to the file.
This line is indented.
EOF
Note that the final 'EOF' (The LimitString
) should not have any whitespace in front of the word, because it means that the LimitString
will not be recognized.
(请注意,最后的'EOF'( LimitString
)在单词前不应有任何空格,因为这意味着LimitString
将不会被识别。)
In a shell script, you may want to use indentation to make the code readable, however this can have the undesirable effect of indenting the text within your here document.
(在shell脚本中,您可能希望使用缩进来使代码可读,但是这样做可能会对缩进here文档中的文本产生不良影响。)
In this case, use <<-
(followed by a dash) to disable leading tabs ( Note that to test this you will need to replace the leading whitespace with a tab character , since I cannot print actual tab characters here.) (在这种情况下,请使用<<-
(后接破折号)来禁用前导制表符( 请注意 ,要进行测试,您需要用制表符替换前导空格 ,因为我无法在此处打印实际的制表符。))
#!/usr/bin/env bash
if true ; then
cat <<- EOF > /tmp/yourfilehere
The leading tab is ignored.
EOF
fi
If you don't want to interpret variables in the text, then use single quotes:
(如果您不想解释文本中的变量,请使用单引号:)
cat << 'EOF' > /tmp/yourfilehere
The variable $FOO will not be interpreted.
EOF
To pipe the heredoc through a command pipeline:
(要通过命令管道传递heredoc:)
cat <<'EOF' | sed 's/a/b/'
foo
bar
baz
EOF
Output:
(输出:)
foo
bbr
bbz
... or to write the the heredoc to a file using sudo
:
(...或使用sudo
将Heredoc写入文件:)
cat <<'EOF' | sed 's/a/b/' | sudo tee /etc/config_file.conf
foo
bar
baz
EOF
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…