views:

1614

answers:

10

How can I print the date which is a day before current time in Bash?

+7  A: 

if you have GNU date and i understood you correctly

$ date +%Y:%m:%d -d "yesterday"
2009:11:09

or

$ date +%Y:%m:%d -d "1 day ago"
2009:11:09
ghostdog74
I found most are as suggested answer but -d switch is not found in Solaris's date
conandor
+4  A: 
date --date='-1 day'
silent
A: 

You can use the date command:

date --date 'yesterday' +%F
Phil Ross
A: 
#!/bin/bash
OFFSET=1;
eval `date "+day=%d; month=%m; year=%Y"`
# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=`expr $day - $OFFSET`
if [ $day -le 0 ] ;then
month=`expr $month - 1`
if [ $month -eq 0 ] ;then
year=`expr $year - 1`
month=12
fi
set `cal $month $year`
xday=${$#}
day=`expr $xday + $day`
fi
echo $year-$month-$day
medoix
bash is actually stated twice in the question.
Peter Lindqvist
thanks peter updated.
medoix
+1 for correction, interesting method, even though it's a bit verbose.
Peter Lindqvist
A: 
yesterday=`date -d "-1 day" %F`

Puts yesterday's date in YYYY-MM-DD format into variable $yesterday.

Heinzi
A: 

Advanced Bash-scripting Guide

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

For details about the date format see the man page for date

date --date='-1 day'
Peter Lindqvist
A: 

date --date='-1 day'

DigitalRoss
A: 
date +%Y:%m:%d|awk -vFS=":" -vOFS=":" '{$3=$3-1;print}'
2009:11:9
What about if today is the 1st January?
martin clayton
+2  A: 

Use Perl instead perhaps?

perl -e 'print scalar localtime( time - 86400 ) . "\n";'

Or, use nawk and (ab)use /usr/bin/adb:

nawk 'BEGIN{printf "0t%d=Y\n", srand()-86400}' | adb

Came across this too ... insane!

/usr/bin/truss /usr/bin/date 2>&1 | nawk -F= '/^time\(\)/ {gsub(/ /,"",$2);printf "0t%d=Y\n", $2-86400}' | adb
martin clayton
+1  A: 

Sorry not mentioning I on Solaris system. As such, the -date switch is not available on Solaris bash.

I find out I can get the previous date with little trick on timezone.

DATE=`TZ=MYT+16 date +%Y-%m-%d_%r`
echo $DATE
conandor