You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求协助排查Shell脚本生成HTML表格报错问题

排查Shell脚本生成HTML表格的报错问题

输入文件内容

inputfile.txt内容如下:

Link Status on Sales Server : down : down
Link Status on HR Server : UP : Up5w0d

原脚本代码

运行报错的脚本:

#!/bin/bash

awk -F' : ' '
    BEGIN{
print "<html>
   <head>
      <style>
         table  {
            border-collapse: collapse;
         }
         table th {
            text-align: left;
            background-color: #3a6070;
            color: #FFF;
            padding: 4px 30px 4px 8px;
         }
         table td {
            border: 1px solid #e3e3e3;
            padding: 4px 8px;
         }
         table tr:nth-child(odd) td {
            background-color: #e7edf0;
         }


      </style>
   </head>

   <body>
      <h1>Site Status</h1>
      <table>
         <tr>
            <th>Description</th>
            <th>Status</th>
                        <th>UPTime</th>
         </tr>"
         }
         {
     print "<tr>"
     for(i=1;i<=NF;i++)
       print "<td>" $i "</td>"
     print "</tr>"
  }
  END{
    print "</table></body></html>"
  }
' inputfile.txt > Output.html

报错原因

  1. awk语法错误:awk不支持在单个print语句中直接写多行未转义的字符串,原BEGIN块中的多行字符串会触发语法报错。
  2. HTML实体错误:脚本中使用<和>会导致生成的HTML显示实体字符,而非实际的标签,无法正确渲染表格。

修复后的脚本

#!/bin/bash

awk -F' : ' '
BEGIN {
    print "<html>"
    print "   <head>"
    print "      <style>"
    print "         table  {"
    print "            border-collapse: collapse;"
    print "         }"
    print "         table th {"
    print "            text-align: left;"
    print "            background-color: #3a6070;"
    print "            color: #FFF;"
    print "            padding: 4px 30px 4px 8px;"
    print "         }"
    print "         table td {"
    print "            border: 1px solid #e3e3e3;"
    print "            padding: 4px 8px;"
    print "         }"
    print "         table tr:nth-child(odd) td {"
    print "            background-color: #e7edf0;"
    print "         }"
    print "      </style>"
    print "   </head>"
    print "   <body>"
    print "      <h1>Site Status</h1>"
    print "      <table>"
    print "         <tr>"
    print "            <th>Description</th>"
    print "            <th>Status</th>"
    print "            <th>UPTime</th>"
    print "         </tr>"
}
{
    print "         <tr>"
    for(i=1; i<=NF; i++) {
        print "            <td>" $i "</td>"
    }
    print "         </tr>"
}
END {
    print "      </table>"
    print "   </body>"
    print "</html>"
}' inputfile.txt > Output.html

修复要点

  • 将BEGIN块中的多行字符串拆分为独立的print语句,符合awk语法规范。
  • 替换&lt;/&gt;为实际的</>,确保生成可正常渲染的HTML标签。
  • 统一代码缩进,提升可读性,避免潜在的语法问题。

内容的提问来源于stack exchange,提问作者anukalps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:30:50