如何在Bash脚本中将Here文档写入文件?
阅读《高级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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句