击:通过日期循环 [英] Bash: Looping through dates

查看:183
本文介绍了击:通过日期循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的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.

如何猛砸实现?

更新

尼斯到拥有:previous运行完成之前没有工作应启动。在这种情况下,当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.

例如。我可以纳入等待%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的符号边日期(不删除前导零)的。要检查是否有有效的输入数据,并将其强制为有效形式如果可能的话,你可以使用日期以及

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 为前 $结束日期,如果你只想到了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

这位前pression $(日期-d$ D+%Y%M%D)转换 $ d个为数字形式,即 2015年2月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.

这篇关于击:通过日期循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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