使用shell中的循环用cat写多行

时间:2014-02-17 09:30:44

标签: bash shell cat

我有这个脚本

 for ((i=0 ; $i<=$c ; i++))
 do
 cat <<"EOF" >my_file.html
 line 1
 line 2
 ...
 EOF
 done

应该在每个循环中写一些特定的行,但我的文件是空的,我总是得到这个错误

syntax error: unexpected end of file

在这个循环之前,我还有另一种猫的用途

cat <<"EOF" >my_file.html
line1
...
line n
EOF

运行脚本后,my_file.html包含这n行但没有循环行。

2 个答案:

答案 0 :(得分:2)

你的语法错了。

分隔符之前有一个空格表示here-doc的结尾。

 cat <<"EOF" >my_file.html
 line 1
 line 2
 ...
EOF     # Remove the leading space from this line.

此外,如果您想在循环中重定向,您可能希望追加 >>,而不是重定向>

答案 1 :(得分:0)

确保EOF分隔符之前或之后没有任何空格,否则shell将无法找到here-document的末尾,您将获得unexpected end of file错误。

此行应仅包含分隔符字(EOF),而不包含任何其他内容。甚至没有评论。

cat <<"EOF" >my_file.html
line 1
line 2
EOF
# there should not be any whitespace around EOF on the line above
相关问题