如何在 Bash 脚本中将 heredoc 写入文件? [英] How can I write a heredoc to a file in Bash script?

查看:35
本文介绍了如何在 Bash 脚本中将 heredoc 写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将此处的文档写入 Bash 脚本中的文件?

How can I write a here document to a file in Bash script?

推荐答案

阅读高级 Bash 脚本指南 第 19 章.这里是文档.

Read the Advanced Bash-Scripting Guide Chapter 19. Here Documents.

这是一个将内容写入位于 /tmp/yourfilehere

Here's an example which will write the contents to a file at /tmp/yourfilehere

cat << EOF > /tmp/yourfilehere
These contents will be written to the file.
        This line is indented.
EOF

注意最后的'EOF'(LimitString)在单词前面不应该有任何空格,因为这意味着LimitString将不被识别.

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.

在 shell 脚本中,您可能希望使用缩进来使代码可读,但是这可能会导致在此处文档中缩进文本的不良影响.在这种情况下,使用 <<-(后跟一个破折号)来禁用前导标签(注意,要测试这一点,您需要替换前导标签带有制表符的空格,因为我无法在此处打印实际的制表符.)

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

通过命令管道管道传递heredoc:

To pipe the heredoc through a command pipeline:

cat <<'EOF' |  sed 's/a/b/'
foo
bar
baz
EOF

输出:

foo
bbr
bbz

... 或使用 sudo 将 heredoc 写入文件:

... or to write the the heredoc to a file using sudo:

cat <<'EOF' |  sed 's/a/b/' | sudo tee /etc/config_file.conf
foo
bar
baz
EOF

这篇关于如何在 Bash 脚本中将 heredoc 写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆