如何使用Bash遍历日期? [英] How to loop through dates using Bash?

查看:84
本文介绍了如何使用Bash遍历日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的bash脚本:

I have such bash script:

array=( '2015-01-01', '2015-01-02' )

for i in "${array[@]}"
do
    python /home/user/executeJobs.py {i} &> /home/user/${i}.log
done

现在我想遍历日期范围,例如2015年1月1日至2015年1月31日.

Now I want to loop through a range of dates, e.g. 2015-01-01 until 2015-01-31.

如何在Bash中实现?

How to achieve in Bash?

更新:

必备:在上一次运行完成之前,不应启动任何作业.在这种情况下,当executeJobs.py完成bash提示时,将返回$.

Nice-to-have: No job should be started before a previous run has completed. In this case, when executeJobs.py is completed bash prompt $ will return.

例如我可以在循环中加入wait%1吗?

e.g. could I incorporate wait%1 in my loop?

推荐答案

使用GNU日期:

d=2015-01-01
while [ "$d" != 2015-02-20 ]; do 
  echo $d
  d=$(date -I -d "$d + 1 day")
done

请注意,因为这使用字符串比较,所以它需要边缘日期的完整ISO 8601表示法(请勿删除前导零).要检查有效的输入数据并在可能的情况下将其强制转换为有效的格式,还可以使用date:

Note that because this uses string comparison, it requires full ISO 8601 notation of the edge dates (do not remove leading zeros). To check for valid input data and coerce it to a valid form if possible, you can use date as well:

# slightly malformed input data
input_start=2015-1-1
input_end=2015-2-23

# After this, startdate and enddate will be valid ISO 8601 dates,
# or the script will have aborted when it encountered unparseable data
# such as input_end=abcd
startdate=$(date -I -d "$input_start") || exit -1
enddate=$(date -I -d "$input_end")     || exit -1

d="$startdate"
while [ "$d" != "$enddate" ]; do 
  echo $d
  d=$(date -I -d "$d + 1 day")
done

最后一个加法:要检查$startdate$enddate之前,如果您只希望看到介于1000年和9999年之间的日期,则可以像这样简单地使用字符串比较:

One final addition: To check that $startdate is before $enddate, if you only expect dates between the years 1000 and 9999, you can simply use string comparison like this:

while [[ "$d" < "$enddate" ]]; do

为了在10000年以后保持非常安全的状态,当字典比较出现问题时,请使用

To be on the very safe side beyond the year 10000, when lexicographical comparison breaks down, use

while [ "$(date -d "$d" +%Y%m%d)" -lt "$(date -d "$enddate" +%Y%m%d)" ]; do

表达式$(date -d "$d" +%Y%m%d)$d转换为数字形式,即2015-02-23变为20150223,并且想法是可以对该数字中的日期进行数字比较.

The expression $(date -d "$d" +%Y%m%d) converts $d to a numerical form, i.e., 2015-02-23 becomes 20150223, and the idea is that dates in this form can be compared numerically.

这篇关于如何使用Bash遍历日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆