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' 202210
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 31 $ date +%Y%m -d "31 day ago" 202209
To put in your scripts:
lastmonth=$(date +%Y%m -d "$(date +%d) day ago")