2

I would like to write a bash script that prints out the date in the following format:

20120205_16
(year)(month)(day)_(24 hour)

so the command to do this for the current date is:

date +'20%y%m%d_%H'

What i would like to do is print every date like this (using a for loop or something) from a specified date to another. For example:

20120205_16 -> 20120305_18 would be:

20120205_16
20120205_17
20120205_18
...
20120305_17
20120305_18

Is it possible to do this easily with date or another method?

1

1 Answer 1

3

Print every date between a Time duration

  1. I would grab your date1 and date2 and convert them to timestamps
  2. Then I would investigate: whats 1 hour converted to timestamp.
  3. And write a for-loop from timestamp(date1) to timestamp(date2)

within the loop I would add step by step timestamp(1 hour), convert the new timestamp back in the prefered date/time format and print it out until the loop ends. #

#!/bin/bash
# by user85321 @ ask ubuntu
# call: ./script.sh 20120205_16 20120205_16 20120305_18

# STEP 1:
# set userdefined Dateformat to normal
d1=$(echo "$1" | sed 's/_/ /g')
d2=$(echo "$2" | sed 's/_/ /g')

# set normalized dates to timestamps
t1=$(date --utc --date "$d1" +%s)
t2=$(date --utc --date "$d2" +%s)

# STEP 2:
# time increment, 1h = 3600 s
h=3600

# STEP 3:
if [ $t2 -gt $t1 ]
then
    for i in $(seq $t1 $h $(($t2-$h)))
    do  
        # take this and do what you want to do ;o)      
        echo $(date --date="@$i" "+%Y%m%d_%H")
    done
fi

My bash prints out exactly that list , what you described . So, it is done. I think some cracks would do it shorter/ better, but it works ...

good luck

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .