You are here

Getting the date of last month in bash

I confess: I tend to overcomplicate things just because that's how I know how to do it.

Example: When I need the date of 2 months ago in a bash script, I usually do date +%s to get the current date and time in seconds since epoch, then subtract 5184000 seconds of that number (60 days) and then use the date command again to get the date formatted the way I want.

Today, I needed to create a script that cleans-up some data older than 2 months. Using the find command with -mtime -60 was not an option so I checked the man page of date to see if date could do the date calculation itself.

I wish I had done this earlier...

date --date="2 months ago"

You can also do things like:

date --date="last month"
date --date="yesterday"
date --date="3 days ago"