0

I am trying to get last n months first and last date given a specific date. Let's say i have a date as today. so for the given date my last date will be today's date and first date will be 1st of the month, for previous month the first date will be 1 and last date will be 31 and so on.

also saw this post but this only helps with month and not the dates. Using `date` command to get previous, current and next month

is there a way we can do this in bash?

ben
  • 1,404
  • 8
  • 25
  • 43

1 Answers1

1

Assuming your date command supports -d option, would you please try the following:

#!/bin/bash

n=3                                                     # show last n months
for (( i = -n + 1; i <= 0; i++ )); do                   # loop over last n months
    y=$(LC_ALL=C date -d "$i month" +%Y)                # year of i months before
    m=$(LC_ALL=C date -d "$i month" +%m)                # month of i months before
    if (( flag )); then                                 # skip the initial month
        echo -n "last: "
        LC_ALL=C date -d "$y/$m/1 -1 day" "+%x %a"      # last day of previous month
    fi
    echo -n "first:"
    LC_ALL=C date -d "$y/$m/1" "+%x %a"                 # first day of the month
    flag=1                                              # set the flag
done
echo -n "last: "
LC_ALL=C date "+%x %a"                                  # today as last day of this month

The output will look like:

first:09/01/22 Thu
last: 09/30/22 Fri
first:10/01/22 Sat
last: 10/31/22 Mon
first:11/01/22 Tue
last: 11/07/22 Mon
tshiono
  • 21,248
  • 2
  • 14
  • 22