在bash中将多行文本回显到文件中?

Ric*_*ard 5 bash shell command-line shell-script

我怎么写:

$count = mysql_num_rows($result);
print "<h3>$count metal prices available</h3>";
Run Code Online (Sandbox Code Playgroud)

到一个文件,index.php?

我试过了:

echo "$count = mysql_num_rows($result);
print "<h3>$count metal prices available</h3>";" > index.php
Run Code Online (Sandbox Code Playgroud)

但我不明白如何转义输入中的双引号。

使用 echo 以外的东西会更好吗?如果可能,我宁愿不重写整个 PHP 脚本(它比示例中给出的 2 行还长!)。

ktf*_*ktf 13

有几种方法可以做到这一点:

 cat >index.php <<'EOT'
 $count = mysql_num_rows($result);
 print "<h3>$count metal prices available</h3>";
 EOT
Run Code Online (Sandbox Code Playgroud)

或者

 echo '$count = mysql_num_rows($result);
 print "<h3>$count metal prices available</h3>";' > index.php
Run Code Online (Sandbox Code Playgroud)

或者

 echo '$count = mysql_num_rows($result);' >index.php  # overwrites file if it already exists
 echo 'print "<h3>$count metal prices available</h3>";' >>index.php  # appends to file
Run Code Online (Sandbox Code Playgroud)

有更多可能的方法 - 以此作为测试事物的起点......


Jon*_*Lin 3

在 bash 中,您需要做的就是将外引号替换为单引号:

echo '$count = mysql_num_rows($result);                                                                  
print "<h3>$count metal prices available</h3>";' > index.php
Run Code Online (Sandbox Code Playgroud)

如果您需要做更复杂的事情,您可以使用“>>”多次回显,它会附加而不是覆盖:

echo '$count = mysql_num_rows($result);' >> index.php
echo 'print "<h3>$count metal prices available</h3>";' >> index.php
Run Code Online (Sandbox Code Playgroud)