如何编写shell脚本从指定起始日期到当前日期每日调用另一个脚本
实现方案
不需要手动处理月份天数、闰年逻辑,直接借助系统自带的date命令处理日期计算即可,以下是兼容大部分GNU/Linux环境的实现:
#!/bin/bash # 配置起始日期,格式为YYYY-MM-DD,按需修改即可 START_DATE="2020-02-01" # 计算起始日期的秒级时间戳 current_ts=$(date -d "$START_DATE" +%s) # 计算当前日期0点的时间戳,避免重复执行当日任务 end_ts=$(date -d "$(date +%Y-%m-%d)" +%s) # 循环遍历每一天 while [ $current_ts -le $end_ts ]; do # 把时间戳转换为年、月、日三个独立参数 year=$(date -d "@$current_ts" +%Y) month=$(date -d "@$current_ts" +%m) day=$(date -d "@$current_ts" +%d) # 调用update.sh脚本 echo "执行update.sh:$year $month $day" ./update.sh "$year" "$month" "$day" # 时间戳加1天(86400秒) current_ts=$((current_ts + 86400)) done
如果是macOS/BSD环境,date命令参数存在差异,使用以下版本即可:
#!/bin/bash START_DATE="2020-02-01" current_ts=$(date -j -f "%Y-%m-%d" "$START_DATE" +%s) end_ts=$(date -j -f "%Y-%m-%d" "$(date +%Y-%m-%d)" +%s) while [ $current_ts -le $end_ts ]; do year=$(date -r $current_ts +%Y) month=$(date -r $current_ts +%m) day=$(date -r $current_ts +%d) echo "执行update.sh:$year $month $day" ./update.sh "$year" "$month" "$day" current_ts=$((current_ts + 86400)) done
- 所有日期计算逻辑由系统自带工具完成,自动适配跨月、跨年、闰年场景
- 仅需要调整
START_DATE变量即可修改起始执行日期
内容的提问来源于stack exchange,提问作者Paul Taylor
相关产品推荐
相关产品推荐

