Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

bash - 如何在Bash脚本中将Heredoc写入文件?(How can I write a heredoc to a file in Bash script?)

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

  ask by Joshua Enfield translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...