使用 cat 在非交互式 bash 脚本中重定向到文件时标记文件结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12466786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
marking end of file while redirecting to a file in a non-interactive bash script using cat
提问by none
I'm trying to redirect a multi-line string to a file. The string contains special chars like quotaand looks like this:
我正在尝试将多行字符串重定向到文件。该字符串包含诸如配额之类的特殊字符,如下所示:
import "this"
import "that"
main() {
println("some text here");
}
I can use echosuch as:
我可以使用echo例如:
echo "import \"this\"
import \"that\"
main() {
println(\"some text here\");
}" > myfile.txt
The problem with this approach is that I need to escape all quotachars. I thought about using catto eliminate the need for escaping. It works well in interactive shells so that I can type cat > myfile.txtand then write my string without escaping and then mark the end of file with <control>d.
这种方法的问题是我需要转义所有配额字符。我想过使用cat来消除逃避的需要。它在交互式 shell 中运行良好,因此我可以键入cat > myfile.txt然后写入我的字符串而无需转义,然后用<control>d.
How can I mark EOFin the script without the actual key sequence <control>d?
如何EOF在没有实际按键序列的情况下在脚本中进行标记<control>d?
回答by Jonathan Leffler
Use a 'here document':
使用“此处文档”:
cat <<'EOF' > myfile.txt
import "this"
import "that"
main() {
println("some text here");
}
EOF
The quotes around the initial 'EOF' mean "do not expand any shell variables (etc) in the here document".
初始'EOF'周围的引号表示“不要在此处的文档中扩展任何shell变量(等)”。

