Dvusrgme
Dvusrgme

Reputation: 389

Bash loop through date time +%Y-%m-%d %H:%M format

Purpose of this code is to print 1 minute interval from an hour ago. I have below code, but having trouble looping between the from and to date

to_dt=`date "+%Y-%m-%d %H:%M"`
from_dt=`date -d "${to_dt} 1 hour ago"  "+%Y-%m-%d %H:%M"`

echo $from_dt $to_dt

2017-08-04 01:54 2017-08-04 02:54

while [ "${from_dt}" -lt "${to_dt}" ] 
do
    
    from_dt=`date -d "${from_dt} 1 minute" "+%Y-%m-%d %H:%M"`
    end_dt_min_after=`date -d "${from_dt} 1 minute" "+%Y-%m-%d %H:%M"`
    
done

I get below error

line 10: [: 2017-08-04 02:01: integer expression expected

Expected result:

2017-08-04 01:55 2017-08-04 02:56

2017-08-04 01:56 2017-08-04 02:57

....

....

is it possible to iterate using while i.e. increment from date by 1 minute during each loop ?

Upvotes: 0

Views: 7006

Answers (3)

asatsi
asatsi

Reputation: 472

I have used epoc for simplicity here. Should work for your use case:

#!/bin/sh

if [ -z $1 ];then
echo Please pass number of seconds
exit 1
fi

epoc_now=`date "+%s"`

epoc_after_hour=`expr $epoc_now + $1`

while [ "${epoc_after_hour}" -gt "${epoc_now}" ]
do
        epoc_now=`expr $epoc_now + 60`
        date -d "@$epoc_now"
done

Upvotes: 1

Gonzalo Herreros
Gonzalo Herreros

Reputation: 309

I would handle numeric timestamps until the time of printing. So you start with:

from_dt=$(($(date +%s -d "1 hour ago")))
to_dt=$(($(date +%s)))

In the loop increment from_dt by 60 each time and then print the timestamp in readable format:

echo "$(date -d @$from_dt)"

Upvotes: 1

anubhava
anubhava

Reputation: 785068

-lt operator expects both operands to be integer.

You should convert your date variables to EPOCH seconds value before running a loop.

to_dt=$(date "+%s")
from_dt=$(date -d "@$to_dt" -d "-1 hour"  "+%s")

while [ "$from_dt" -lt "$to_dt" ]; do
   # add 1 minute
   from_dt=$(date -d "@$from_dt" -d "+1 minute" '+%s')
   echo "inside the loop"
done

Upvotes: 0

Related Questions