Link to home
Start Free TrialLog in
Avatar of tballah
tballah

asked on

In bash shell how can I convert from today date to yesterday date?

Dear Experts:

I want to write a bash script to do backup a folder under format YYYYMMDD. This script will be run today but it will do a backup of yesrday folder. For example here are the list of folder
20080306
20080307
20080308

I use command CURRENT_DAY=`date '+20%y%m%d'` the output is 20080308 but I want to do a backup on 20080307. What should I code for the variable BACKUP_DAY. Is there anything similar to a function in VBScript named datediff()?
#!/usr/bin/bash
CDR_DIR=/var/backsave/R4/scdr
CURRENT_DAY=`date '+20%y%m%d'`
#What should I code here
BACKUP_DAY=
cd $CDR_DIR
if [`pwd` != "$CDR_DIR"]
then
	echo "Cannot change directory to $CDR_DIR"
else
	
fi

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Tintin
Tintin

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tballah
tballah

ASKER

I found a flexible solution to shift the number of days behind the current by mixing the code with Perl. Here it is

BACKUP_DAY=`perl -e "use POSIX qw(strftime); print strftime('%Y%m%d', localtime(time -86400)), qq(\n);"`

where (1 day) * (24 hrs) * (3600 s) = 86400

Ref: OReilly.bash.Cookbook.May.2007
Solution was provided for shell as the question was focused on bash, but the asker choose to use perl rather bash.

If your locale uses daylight saving time, there may be two hours per year when that doesn't work
To take care of those cases, you can
BACKUP_DAY=`perl -MPOSIX -e 'print strftime"%Y%m%d\n", localtime(time -43200-3600*(localtime)[2])'`
Tintin, nice approach with TZ! Good to know.
I see the only problem with winter/summer time, but the same problem present in authors' self answer (24 hours earlier doesn't mean previous YYYYMMDD date, because at least once a year we have a day with 25 hours in localtime and once a yaer wi have a day with 23 hours, so the resulting date may be as the same day as 2 days before).


Split executed.

modus_operandi
EE Moderator
just cuz I can. I use debian and this method does what you want without touching the timezone.

date -d "-1 day" +%Y%m%d
I know after verifying echo "Bash version ${BASH_VERSION}..."
I was able to run
yesterday=`/bin/date "+%m%d%y" --date="1 days ago"`


hth