如何完善Bash脚本,生成含文件名、修改日期及延期30天的HTML表格?
修正后的Bash脚本实现
#!/bin/bash head='<!DOCTYPE html> <html> <div class="u-expanded-width u-table u-table-responsive u-table-1"> <table class="u-table-entity u-table-entity-1"> <colgroup> <col width="33.3%"> <col width="33.3%"> <col width="33.3%"> </colgroup> <thead class="u-align-center u-custom-font u-grey-5 u-heading-font u-table-header u-table-header-1"> <tr style="height: 40px;"> <th class="u-border-1 u-border-grey-dark-1 u-table-cell">Community String</th> <th class="u-border-1 u-border-grey-dark-1 u-table-cell">Simulation Created</th> <th class="u-border-1 u-border-grey-dark-1 u-table-cell">Simulation Expires</th> </tr> </thead> <tbody class="u-align-center u-table-body">' tail='</tbody> </table> </div> </html>' printf '%s\n' "$head" shopt -s nullglob # 统一目标目录路径,确保遍历和操作的是同一批文件 target_dir="/usr/local/snmpsim/data/ephemeral" for file in "$target_dir"/*.snmprec; do # 提取无后缀文件名 [[ $file =~ ([^/]+)\.snmprec$ ]] || continue Filename=${BASH_REMATCH[1]} # 获取文件最后修改时间,格式与示例保持一致 mtime_ts=$(stat -c %Y "$file") SimulationCreated=$(date -d "@$mtime_ts" "+%a %d %b %I:%M:%S %p %Z") # 计算修改时间加30天后的日期 SimulationExpires=$(date -d "@$mtime_ts +30 days" "+%a %d %b %I:%M:%S %p %Z") # 输出标准表格行 printf ' <tr>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n </tr>\n' "$Filename" "$SimulationCreated" "$SimulationExpires" done printf '%s\n' "$tail"
原脚本问题分析
- 路径不统一:原脚本中
find命令指向/usr/local/data/,但循环遍历的是/usr/local/snmpsim/data/ephemeral/,导致日期与文件完全不匹配。 - 日期批量获取逻辑错误:提前用
find把所有文件的日期存入变量,循环时每个文件复用该变量,导致所有日期被塞进同一个单元格,直接破坏表格结构。 - 过期日期计算错误:
find -mtime +30是筛选修改时间超过30天的文件,并非给当前文件的修改时间加30天。 - HTML标签冗余:原日期变量中包含
<tr><td>标签,输出时会嵌套在表格行内,造成HTML结构混乱。
修正要点说明
- 统一目录路径:定义
target_dir变量,确保遍历和操作的是同一目录下的文件。 - 逐文件处理日期:在循环内部单独处理每个文件的修改时间,用
stat获取时间戳后通过date格式化,保证每个文件的日期对应准确。 - 正确计算过期日期:利用
date -d "@时间戳 +30 days"直接计算修改时间加30天后的日期,格式与原修改时间保持一致。 - 清理冗余HTML标签:日期变量仅存储纯文本日期,在
printf时统一输出<td>标签,确保表格结构规范。
内容的提问来源于stack exchange,提问作者divad
相关产品推荐
相关产品推荐

