简体   繁体   中英

Loop minutes and echo with bash

I want to iterate all the minutes in a month (the purpose will be to generate a CSV file).

But when I try this:

d="2016-09-01 00:00:00"
 while [ "$d" != "2016-09-30 00:00:00" ]; do
 echo $d 
 d=$(date --utc "+%Y-%m-%d %H:%M:00" -d "$d + 1 minute" )
done

Both the hour and minute are being incremented:

2016-09-01 00:00:00
2016-09-01 01:01:00
2016-09-01 02:02:00
2016-09-01 03:03:00
2016-09-01 04:04:00
2016-09-01 05:05:00
2016-09-01 06:06:00
2016-09-01 07:07:00
2016-09-01 08:08:00

What am I doing wrong and how to correctly loop minutes?

I would work with Unix timestamps instead.

d=$(date --utc +%s -d "2016-09-01 00:00:00")
end=$(date --utc +%s -d "2016-09-30 00:00:00")
while [ "$d" != "$end" ]; do
    date --utc "+%Y-%m-%d %H:%M:00" -d "@$d"
    d=$(( d + 60 ))
done

You can add timezone UTC after your date string variable $d to get the right output:

d="2016-09-01 00:00:00"
for ((i=0; i<=60; i++)); do
   date --utc -d "$d UTC + $i minute"
done

Thu Sep  1 00:00:00 UTC 2016
Thu Sep  1 00:01:00 UTC 2016
Thu Sep  1 00:02:00 UTC 2016
Thu Sep  1 00:03:00 UTC 2016
Thu Sep  1 00:04:00 UTC 2016
Thu Sep  1 00:05:00 UTC 2016
...
...
Thu Sep  1 00:55:00 UTC 2016
Thu Sep  1 00:56:00 UTC 2016
Thu Sep  1 00:57:00 UTC 2016
Thu Sep  1 00:58:00 UTC 2016
Thu Sep  1 00:59:00 UTC 2016
Thu Sep  1 01:00:00 UTC 2016

Note use of UTC after $d .

Using + after a time component in the date string is used for ' time zone correction ' not for doing what you want to do. Interestingly, inverting date and time works:

$ date  "+%Y-%m-%d %H:%M:00" -d "21:31:00 2016-09-03 + 1 minute  "
2016-09-03 21:32:00

while the other way around messes with timezones and offsets so the result might depend on your local configuration:

$ TZ=Europe/London date  "+%Y-%m-%d %H:%M:00" -d "2016-09-03 21:32:00 + 1 minute "
2016-09-03 21:33:00
$ TZ=Europe/Brussels date  "+%Y-%m-%d %H:%M:00" -d "2016-09-03 21:32:00 + 1 minute "
2016-09-03 22:33:00
$ TZ=Asia/Singapore date  "+%Y-%m-%d %H:%M:00" -d "2016-09-03 21:32:00 + 1 minute "
2016-09-04 04:33:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM