Shell Script: Calculate Yesterday’s Date on UNIX

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:

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:

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

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }