Bash按1小时步长循环生成时间区间执行API调用的语法错误排查
修正后的实现方案
可直接运行代码
# 定义目标日期 target_date='20210825' # 遍历0到23小时 for hour in {0..23} do # 生成当前区间起始时间戳(毫秒级,末尾补3个0) start_time=$(date -d "$target_date + $hour hour" +%s)"000" # 生成当前区间结束时间戳 next_hour=$((hour + 1)) stop_time=$(date -d "$target_date + $next_hour hour" +%s)"000" # 打印时间区间和参数,可按需删除 printf "当前处理区间:%02d:00-%02d:00\nstart_time=%s\nstop_time=%s\n---\n" $hour $next_hour $start_time $stop_time # 此处填写实际API调用逻辑,直接使用$start_time和$stop_time变量即可 done
核心修复说明
- 补充Bash for 循环必须的
do、done关键字,修复基础语法错误 - 调整date命令
-d参数的拼接格式为标准的"日期 + N hour"写法,避免参数解析失败 - 使用算术展开
$((hour + 1))完成数值递增计算,避免原写法中i+1被识别为普通字符串的问题 - 给所有参数、变量加上双引号,避免空格或特殊字符引发的异常
- 移除原代码中日期赋值多余的
$符号,符合普通字符串赋值语法
如果你使用的是macOS系统,自带的BSD date命令语法和GNU date不同,需要将date部分替换为如下写法:
start_time=$(date -v${hour}H -j -f "%Y%m%d" "$target_date" +%s)"000" stop_time=$(date -v${next_hour}H -j -f "%Y%m%d" "$target_date" +%s)"000"
内容的提问来源于stack exchange,提问作者bullfighter
相关产品推荐
相关产品推荐

