Last date of the previous month - Bash

Viewed 51

I want to get the Last date of the previous month and the code I'm using is date -d "$(2022-04-30 +%Y%m01) -1 month" +%Y-%m-%d. The output I'm getting is 2022-04-24 instead of 2022-03-31. I'm using Debian Linux.

2 Answers
# last day of last month
date -d "$(date +%d) days ago" +%Y-%m-%d
# or
date -d "-$(date +%d) days" +%Y-%m-%d

# last day of this month
date -d "$(date +%d) days ago month" +%Y-%m-%d
# or
date -d "-$(date +%d) days month" +%Y-%m-%d

Try out this one:

last_date=$(date -d "`date +%Y%m01` -1 day" +%Y-%m-%d)
Related