1

I have the following work-in-progress script in bash.

#!/bin/bash
# usage:
# ./script.sh <iso8601_period>


period_ago() {
    if [[ $1 =~ P(([0-9]+)M)?([0-9]+)D ]]; then
        local months=${BASH_REMATCH[2]:-0}
        local days=${BASH_REMATCH[3]}
        date -d "$months months $days days ago" "+%Y/%m/%d"
    fi
}

period="$(period_ago $1)"

max=3
for (( i=0; i <= $max; ++i ))
do
    temp=$i
    if (( ${#temp}  < 2 ))
    then
       temp="0$temp"
    fi

    echo $period/$temp
done

and when you run this, currently, this will print:

2019/07/20/00

2019/07/20/01

2019/07/20/02

2019/07/20/03

I'm trying to figure out if I can do something like this when running the script (passing two arguments) and it will give me dates between two ISO8601 periods, in this case 100-days ago and 99-days ago?

./script P100D P99D

2019/07/20/00

2019/07/20/01

2019/07/20/02

2019/07/20/03

2019/07/21/00

2019/07/21/01

2019/07/21/02

2019/07/21/03

Community
  • 1
  • 1
Saffik
  • 911
  • 4
  • 19
  • 45

1 Answers1

1

Building on the period_ago function and the loop to print 'max' lines on that were already developed:

period_ago {
    ...
}

start=$(period_ago $1)
end=$(period_ago $2)
max=3

d=$start
until [[ $d > $end ]] ; do

# Original Loop to max.
   for (( i=0; i <= $max; ++i )) 
   do
    temp=$i
    if (( ${#temp}  < 2 ))
    then
       temp="0$temp"
    fi

    echo $d/$temp
  done
# Bump to next date
  d=$(date -d "$d tomorrow" +'%Y-%m-%d')

done

More Compact Version

start=$(period_ago $1)
end=$(period_ago $2)
max=3

d=$start
until [[ $d > $end ]] ; do

# Original Loop to max.
   for (( i=0; i <= $max; ++i )) ; do
       printf "%s/%02d\n" $d $i
   done
# Bump to next date
  d=$(date -d "$d tomorrow" +'%Y/%m/%d')

done

dash-o
  • 13,723
  • 1
  • 10
  • 37