我怎样才能写一个heredoc到Bash脚本中的文件?

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


阅读高级Bash脚本指南第19章此处文档。

这是一个将内容写入/tmp/yourfilehere文件的例子

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

请注意,最后的'EOF'(The LimitString )在单词前不应该有空格,因为这意味着LimitString不会被识别。

在shell脚本中,您可能希望使用缩进来使代码可读,但这可能会在您的here文档中产生缩进文本的不良效果。 在这种情况下,使用<<- (后跟破折号)禁用前导制表符( 请注意 ,为了测试此操作,您需要用制表符替换前导空白符 ,因为我无法在此打印实际的制表符。)

#!/usr/bin/env bash

if true ; then
    cat <<- EOF > /tmp/yourfilehere
    The leading tab is ignored.
    EOF
fi

如果您不想解释文本中的变量,请使用单引号:

cat << 'EOF' > /tmp/yourfilehere
The variable $FOO will not be interpreted.
EOF

通过命令管道来管理heredoc:

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

输出:

foo
bbr
bbz

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

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

而不是使用cat和I / O重定向,而是使用tee来代替:

tee newfile <<EOF
line 1
line 2
line 3
EOF

它更简洁,而且与重定向运算符不同,它可以与sudo结合使用,如果需要使用根权限写入文件。


注意:

  • 以下浓缩和组织其他答案,特别是Stefan Lasiewski和Serge Stroobandt的出色工作
  • Lasiewski和我推荐高级Bash脚本指南中的Ch 19(Here Documents)
  • 这个问题(如何在bash脚本中写一个here文档(aka heredoc)到一个文件?)有(至少)3个主要的独立维度或子问题:

  • 你想覆盖现有文件,追加到现有文件还是写入新文件?
  • 您的用户或其他用户(例如root )是否拥有该文件?
  • 你想直接写出你的heredoc的内容,还是让bash在你的heredoc中解释变量引用?
  • (还有其他的维度/子问题我认为不重要,考虑编辑这个答案来添加它们!)下面是上面列出的问题维度的一些更重要的组合,以及各种不同的分隔标识符 - 没有什么神圣的EOF ,只要确保您用作分隔标识符的字符串不会发生在您的heredoc内部:

  • 要覆盖您拥有的现有文件(或写入新文件),请在heredoc内替换变量引用:

    cat << EOF > /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    EOF
    
  • 要附加您拥有的现有文件(或写入新文件),请替换heredoc中的变量引用:

    cat << FOE >> /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    FOE
    
  • 要使用heredoc的文字内容覆盖您拥有的现有文件(或写入新文件):

    cat << 'END_OF_FILE' > /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    END_OF_FILE
    
  • 要使用heredoc的文字内容附加您拥有的现有文件(或写入新文件):

    cat << 'eof' >> /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    eof
    
  • 要覆盖root拥有的现有文件(或写入新文件),请在heredoc内部替换变量引用:

    cat << until_it_ends | sudo tee /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    until_it_ends
    
  • 要追加由user = foo拥有的现有文件(或写入新文件)和heredoc的文字内容:

    cat << 'Screw_you_Foo' | sudo -u foo tee -a /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    Screw_you_Foo
    
  • 链接地址: http://www.djcxy.com/p/56869.html

    上一篇: How can I write a heredoc to a file in Bash script?

    下一篇: Change the current directory from a Bash script