When last month is not last month

When last month is not last month
Photo by Towfiqu barbhuiya / Unsplash

When you type in Linux Bash: date +%Y%m -d '1 months ago', you assume you'll get the year and month of last month.

Well, for a reason that I've got yet to discover (probably very logical), not the case for today's date:

$ date
lundi 31 octobre 2022, 00:11:30 (UTC+0100)
$ date +%Y%m -d '1 months ago'

The workaround I found on Stackoverflow is to count the number of day of the month until today, and substract them from today's date:

$ date +%d
$ date +%Y%m -d "31  day ago"

To put in your scripts:

lastmonth=$(date +%Y%m -d "$(date +%d) day ago")