2

I have been using the command:

date --date='1 months ago' +%b

To get the month name of the month it was a month ago, but have realised today as it is the 31st that this command actually gives me the month name it was 4 weeks ago.

Is there any way to get the calendar month that it was 1 month ago, or indeed n months ago as I can see that the discrepancy will be greater as the number of months is longer.

annavt
  • 713
  • 1
  • 6
  • 8

3 Answers3

1

Date calculations that depend on the number of days in the month are tricky. A hybrid approach, using month numbers and a lookup table, will probably work best.

months=("" Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
echo ${months[$(date +%m) - 1 ]}
chepner
  • 497,756
  • 71
  • 530
  • 681
0
[[ $(date +%d) == "31" ]] && date -d'-31 day' +%b || date -d'-1 month' +%b

test with today:

kent$ date
Thu Jul 31 17:34:27 CEST 2014

kent$ [[ $(date +%d) == "31" ]] && date -d'-31 day' +%b || date -d'-1 month' +%b
Jun
Kent
  • 189,393
  • 32
  • 233
  • 301
0

try this one line

#if the month before 30 days is the same of the actual month ,then return the month before 31 days

[[ `date --date='30 day ago' +%b` == `date +%b` ]] && echo `date --date='31 day ago' +%b` || echo `date --date='30 day ago' +%b`
bachN
  • 592
  • 3
  • 14