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

查看:24
本文介绍了如何使用 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-01-01 至 2015-01-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")

  # mac option for d decl (the +1d is equivalent to + 1 day)
  # d=$(date -j -v +1d -f "%Y-%m-%d" "2020-12-12" +%Y-%m-%d)
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天全站免登陆