Infinity and Beyond
RSS icon Email icon Home icon
  • Finding yesterday’s date in Linux / Unix

    Posted on April 2nd, 2011 Mike No comments

    I recently wrote a set of scripts to backup a production database on a nightly basis. The ultimate goal is to setup a DR site which automatically restores day-old backups. In order to accomplish this, I need to be able to figure out the date for ‘yesterday’, and I didn’t want to resort to using any other code (perl, PHP, python, etc). It turns out that reasonably modern versions of the ‘date’ command can do this for you:

    Today’s Date:

    # date +'%Y-%m-%d'
    2011-04-02

    Yesterday’s Date:

    # date +'%Y-%m-%d' --date='1 day ago'
    2011-04-01

    A month ago:

    # date +'%Y-%m-%d' --date='1 month ago'
    2011-03-02

    You can also convert between timestamps:

    # date +'%s'
    1301786252
    # date --date='@1301786252' +'%Y-%m-%d'
    2011-04-02

    Doing math with timestamps could be useful too:

    # TS=$(date +'%s'); let TS="${TS} - 604800"; date --date="@${TS}" +'%Y-%m-%d'
    2011-03-26