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:

$ 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

Ibrahim is a technology enthusiast with a keen interest in *NIX (Unix, Linux) systems, Android, open source and other tech related stuff. When his cpu load is low, you can probably find him online playing on his Xbox or PlayStation.

  • Why are you using expr?

    External comands are slow and are not necessary for integer arithmetic in a POSIX shell (e.g. bash or dash).

  • ibrahim

    @Chris, The script is not optimised for speed. I believe you are talking about the “$(())” and “let” constructs in bash shell? I believe there are still some machines where these shells are not available and thus using ‘expr’ meant that the script can be run on a wider range of UNIX flavours/machines.

  • Integer arithmetic is part of the standard Unix shell. There are few, if any, systems that do not have it;
    expr is not needed.