I want to find out the past calendar day using bash .
I have tried the following
Today's date :
20130701
Expected Output :20130630
Code1 :
myTime=`TZ=$TZ+24 date +'%Y%m%d'`
echo $myTime
Output
20130629
Code2 :
timeB=$(date +%Y%m)
sysD=$(date +%d)
sysD=$((sysD-1))
echo $timeB$sysD
Output
2013070
Code3 :
yest=$(date --date="yesterday")
echo "$yest"
Output
date: illegal option -- date=yesterday
usage: date [-u] mmddHHMM[[cc]yy][.SS]
date [-u] [+format]
date -a [-]sss[.fff]
Code4 :
$ date +%Y%m%d -d "yesterday"
Output
20130701
None of them gave the correct output . Can anyone please advise me the correct way to get the desired results.
OS Version : SunOS 5.10
You probably have python.
python -c "import datetime; print datetime.date.today () - datetime.timedelta (days=1)"
Though, if date would support the -d
flag, then that would be my preferred solution.
Based on the usage message, I don't think you're on OS X. If you are on OS X, you can use the -v
flag, but only relative to the current date/time:
$ date +%Y%m%d
20130630
$ date -v-1d +%Y%m%d
20130629
If you have ksh
available, you can use it. I'm not sure of the full syntax available so I don't know if you can specify the base date, but you can do it relative to today:
$ ksh -c 'printf "%(%Y%m%d)T\n" yesterday'
20130629
Solaris (as of version 10) still ships with the ridiculously old ksh88
as its default ksh
. You should be able to find ksh93
(which supports the above syntax) in /usr/dt/bin/ksh
:
$ /usr/dt/bin/ksh -c 'printf "%(%Y%m%d)T\n" yesterday'
20130629
If you have tclsh
available, you can use it:
$ echo 'puts [clock format [clock scan "yesterday"] -format %Y%m%d]' | tclsh
20130629
$ echo 'puts [clock format [clock scan "20130701 - 1 day"] -format %Y%m%d]' | tclsh
20130630
You've already said --date
doesn't work, but for completeness: On systems using the GNU version of date
, you can use --date
or -d
:
$ date +%Y%m%d
20130630
$ date +%Y%m%d -d yesterday
20130629
$ date +%Y%m%d -d '-1 days'
20130629
$ date +%Y%m%d -d '20130701 - 1 day'
20130630
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With