octopusgrabbus
octopusgrabbus

Reputation: 10685

Obtaining Yesterday In Bash

Is there an easier way to calculate yesterday in Bash? This code (used for incremental tars)

mod_time=""

if [ ! -z ${1} ]; then
    if [ "${1}" = "i" ]; then

        this_month=`date +%m`

        this_year=`date +%y`

        last_day=`date +%d`

        # Subtract one from today's day, to get yesterday.

        if [ "${last_day:0:1}" = "0" ]; then
            if [ "${last_day:1:1}" > "1" ]; then
                last_day=$[$((${last_day:1:1})) - 1]
            fi
        else
            last_day=$[$(($last_day)) - 1]
        fi

        # zero pad if necessary

        if [ 10 -gt $last_day ]; then
            last_day="0$last_day"
        fi

        mod_time=" --newer-mtime $this_month/$last_day/$this_year "
    fi
fi

has a couple of problems like calculating day 0, and also not doing the right thing at the end of the month. I don't want to build in leap year calculations, and am wondering if there's an easy way to do this in Bash. If not, I'll use Clojure or Python.

Upvotes: 1

Views: 893

Answers (4)

Zsolt Botykai
Zsolt Botykai

Reputation: 51593

Well for me this seems a bit shorter:

date --date "1 day ago"

Upvotes: 2

Kevin
Kevin

Reputation: 56059

date -d yesterday

Upvotes: 2

ajreal
ajreal

Reputation: 47321

This might help

 date -d "yesterday" +%Y%m%d

return

 20120202

Upvotes: 3

FatalError
FatalError

Reputation: 54551

Perhaps I'm missing your point, but why not:

$ date -d yesterday
Wed Feb  1 11:53:12 EST 2012

(might be a GNU extension so no promises you'll have it). If you do, I'd say it's easier :).

Upvotes: 4

Related Questions