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

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

问题描述

如何在Bash脚本中将here文档写入文件?

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

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脚本中,您可能希望使用缩进使代码可读,但是,这会对在here文档中缩进文本产生不良影响.在这种情况下,请使用<<-(后接破折号)来禁用前导标签(注意),要对此进行测试,您需要用制表符替换前导空白 ,因为我无法在此处打印实际的制表符.)

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天全站免登陆