When invoked without arguments, the date command displays the current date and time. Depending on the options specified, the date would set the date and time or print it in a user-defined format. However, how do you get yesterdays with bash shell script? What about tomorrows day? I have seen many sysadmins writing Perl scripts for calculating relative dates such as yesterdays or tomorrows day. You can use the GNU date command  or BSD/date command, which is designed to handle relative date calculation such as:

  • 1 Year
  • 2 Days
  • 2 Days ago
  • 5 Years
  • yesterday
  • tomorrow
  • next week

Let us see how to get yesterday’s date in bash on Linux operating systems.

Getting Yesterday’s or Tomorrow’s Day with bash on Linux or Unix

The syntax and sample examples are as follows:

GNU date syntax to get yesterday’s date in bash

The syntax is as follows:

date  --date="STRING"
date  --date="next Friday"
date  --date="2 days ago"
date  --date="yesterday"
date  --date="yesterday" +"%format"
## Get yesterday's date in dd-mm-yy format
date  --date="yesterday" +"%d-%m-%y"
date  --date="yesterday" +"%m-%d-%y" ## US date format
date  --date="yesterday" +"%Y-%m-%d" ## YYYY-mm-dd format
### store y'day date in a shell variable called yday and display it ##
yday=$(date  --date="yesterday" +"%Y-%m-%d")
echo "$yday"

The --date=STRING is a human-readable format such as “next Thursday” or “1 month ago”. A date string may contain items indicating calendar date, time of day, time zone, day of the week, relative time, relative date, and numbers. See “How To Format Date For Display or Use In a Shell Script” for more about +“%format” stings.

Why use relative GNU/date formats?

  • Ease of use
  • Write your shell scripts
  • Automate task using Linux cron (example run a job on the last day of the month or Nth day of the month or 3rd Friday and so on)

GNU date command examples

First, try to display today’s date, enter:

$ date

Sample outputs:

Wed Jun 15 04:47:45 IST 2011

To display yesterday’s date, enter:

$ date --date="1 days ago"

$ date --date="1 day ago"

$ date --date="yesterday"

$ date --date="-1 day"

Sample outputs:

Tue Jun 14 04:54:40 IST 2011

You can use various string formats to produce the same output. Please note that the output of the date command is not always acceptable as a date string, not only because of the language problem but also because there is no standard meaning for time zone items like IST or EST.

Find tomorrow’s date in bash script on Linux

Type the following command

$ date --date="-1 days ago"

Or

$ date --date="next day"

#linux

Getting Yesterday's or Tomorrow's date with bash on Linux / Unix
1.50 GEEK