There are times when you will need to calculate yesterday’s date in a UNIX shell script to run some date sensitive cron jobs. There are currently no standard command line tools in UNIX to perform such date arithmetic.

Writing a program in C or Java to perform such date arithmetic is actually an overkill. If you have the GNU date command installed, you can get the date quite easily by running date as follows:

$ date -d "-1 day"
Sat Jul  4 16:30:08 MPST 2009

GNU date is available in Linux distributions. It’s not available by default in commercial UNIX distributions such as AIX or Solaris. To calculate yesterday’s date for such platforms, you can use the following script instead. Save the following script to a file called yesterday, chmod to 755 and copy it to a directory in your PATH.

Below are some examples on how the script can be called:

$ date
Sun Jul  5 17:13:12 MPST 2009

$ yesterday

$ yesterday "prefix %Y-%m-%d postfix"
prefix 2009-07-04 postfix

$ yesterday "%Y-%m-%d"

Update (9-Nov-2010): Script updated to run on Solaris platforms

Update (7-Aug-2011): Script updated to prevent printf function from interpreting certain numbers as octal
