How to Get Yesterday's Date in Bash on Mac and Ubuntu

In Bash scripting, there are various ways to retrieve yesterday’s date on both Mac and Ubuntu systems. Below, we’ll demonstrate two different methods for each operating system.

Mac:

Method 1: Using date with -v option

1
2
yesterday=$(date -v-1d +%F)
echo "Yesterday's date on Mac: $yesterday"

In this method, we use the -v option with the date command to subtract 1 day from the current date and format it as %F, which gives the date in YYYY-MM-DD format.

Method 2: Using date with -j option

1
2
yesterday=$(date -j -f "%Y-%m-%d" -v-1d $(date +%Y-%m-%d) +%Y-%m-%d)
echo "Yesterday's date on Mac: $yesterday"

This method involves a bit more complexity but allows you to specify the input date format (%Y-%m-%d) and retrieve yesterday’s date in the same format.

Ubuntu:

Method 1: Using date with “yesterday” string

1
2
yesterday=$(date -d "yesterday" '+%Y-%m-%d')
echo "Yesterday's date on Ubuntu: $yesterday"

On Ubuntu, you can use the -d option with the “yesterday” string to easily obtain yesterday’s date in the YYYY-MM-DD format.

Method 2: Using date with specific time

1
2
yesterday=$(date -d "yesterday 13:00" '+%Y-%m-%d')
echo "Yesterday's date on Ubuntu (at 13:00): $yesterday"

This method allows you to get yesterday’s date at a specific time, in this case, 13:00. You can adjust the time according to your requirements.

Choose the method that best suits your needs and system, and you can easily retrieve yesterday’s date in Bash on both Mac and Ubuntu.

0%