处理CSV中EST格式日期时遇Invalid date错误,求解决方法
解决Bash中EST格式日期转时间戳的无效日期错误
问题
从CSV文件读取EST格式的日期(如Thu Aug 18 18:59:59 EST 2022),使用date -d命令转换为时间戳时出现invalid date错误,同时CSV表头被错误处理导致无效计算结果。
原脚本与错误输出
原Bash脚本
#!/bin/bash set +x date=`/bin/date` TodayDateSec="$(/bin/date "+%s")" while IFS=, read -r Name StartDate EndDate; do if [ -z "$EndDate" ]; then echo "$EndDate details not exists" else echo "Name: $Name; StartDate: $StartDate; EndDate: $EndDate"; EndDateSec="$(/bin/date -d "$EndDate" +'%s')"; DiffDays="$(( ( EndDateSec - TodayDateSec )/86400 ))" echo "***********$DiffDays************" if [[ "$DiffDays" -lt 30 ]]; then echo "Certificate is going to expire in $DiffDays. Please take required action" fi fi done < sample3.csv
执行错误输出
Name: CertName; StartDate: StartDate; EndDate: EndDate /bin/date: invalid date ‘EndDate’ ***********-19195************ Certificate is going to expire in -19195. Please take required action Name: sslcertificates; StartDate: Thu Dec 17 19:00:00 EST 2020; EndDate: Thu Aug 18 18:59:59 EST 2022 /bin/date: invalid date ‘Thu Aug 18 18:59:59 EST 2022’ ***********-19195************ Certificate is going to expire in -19195. Please take required action
解决方案
1. 跳过CSV表头
原脚本会把CSV第一行的表头当成数据处理,导致EndDate字符串被传入date命令报错。在循环开始前先读取并丢弃表头即可:
# 在while循环前添加这一行,跳过表头 read -r header
2. 修复EST时区解析问题
部分系统的date命令对EST这种时区缩写解析不兼容(EST/EDT涉及夏令时切换,缩写可能不被正确识别),可以用两种方法解决:
方法一:替换EST为UTC偏移量
把日期字符串中的EST替换为对应的UTC偏移-0500(东部标准时间比UTC晚5小时):
EndDateSec="$(/bin/date -d "${EndDate//EST/-0500}" +'%s')"
方法二:指定完整时区名称
调用date时通过TZ环境变量指定完整时区(如America/New_York),让命令正确识别时区:
EndDateSec="$(TZ=America/New_York /bin/date -d "$EndDate" +'%s')"
完整修改后的脚本
#!/bin/bash set +x TodayDateSec="$(/bin/date "+%s")" # 跳过CSV表头 read -r header while IFS=, read -r Name StartDate EndDate; do if [ -z "$EndDate" ]; then echo "EndDate details not exists for $Name" else echo "Name: $Name; StartDate: $StartDate; EndDate: $EndDate"; # 使用完整时区解析日期 EndDateSec="$(TZ=America/New_York /bin/date -d "$EndDate" +'%s')"; DiffDays="$(( ( EndDateSec - TodayDateSec )/86400 ))" echo "***********$DiffDays************" if [[ "$DiffDays" -lt 30 && "$DiffDays" -ge 0 ]]; then echo "Certificate is going to expire in $DiffDays days. Please take required action" elif [[ "$DiffDays" -lt 0 ]]; then echo "Certificate has already expired $((-DiffDays)) days ago" fi fi done < sample3.csv
注:额外添加了证书过期后的判断逻辑,避免负数天数的误导提示。
内容的提问来源于stack exchange,提问作者Cho2
相关产品推荐
相关产品推荐

