script to pull files one day old

April 15, 2011 at 12:04:53
Specs: Linux
Script is written, but is looking for files with today's date.... I need files from yesterday.

This works for today -- how do I get it to work for yesterday?

if [ -e /home/$FEEDGROUP/$FEEDGROUP.$DATE ]

DATE is defined as DATE=`date +%Y%m%d`


See More: script to pull files one day old

Report •


#1
April 16, 2011 at 22:36:34
Since you are running Linux, the date command supports converting between seconds from the epoch and a date string. So, get today's seconds from the epoch, subtract 86400 seconds to get yesterday's seconds from the epoch, and convert that number of seconds back to a date string. From there it is a simple case of parsing the date string to get the proper fields for the new $DATE variable.

Let me know if you have any questions:

#!/bin/bash

month_no () {
if [ $1 = "Jan" ]
then
   echo "01"
   return
fi
if [ $1 = "Feb" ]
then
   echo "02"
   return
fi
if [ $1 = "Mar" ]
then
   echo "03"
   return
fi
if [ $1 = "Apr" ]
then
   echo "04"
   return
fi
if [ $1 = "May" ]
then
   echo "05"
   return
fi
if [ $1 = "Jun" ]
then
   echo "06"
   return
fi
if [ $1 = "Jul" ]
then
   echo "07"
   return
fi
if [ $1 = "Aug" ]
then
   echo "08"
   return
fi
if [ $1 = "Sep" ]
then
   echo "09"
   return
fi
if [ $1 = "Oct" ]
then
   echo "10"
   return
fi
if [ $1 = "Nov" ]
then
   echo "11"
   return
fi
if [ $1 = "Dec" ]
then
   echo "12"
   return
fi
echo "0"
} # end function

# seconds since epoch
today=$(date +%s)

# yesterdays seconds since epoch
yesterday=$(($today - 86400))

dstr=$(date -d @$(echo $yesterday) )

set -- $(echo $dstr) # parse yesterday's date string

mymm=$(month_no $2 ) # get the month number
DATE="${6}${mymm}${3}"
echo $DATE # new date is 1 day less i.e. 20110415



Report •

#2
April 18, 2011 at 09:11:18
Thanks. But, believe it or not, I found a much simpler way of getting it to work by entering

DATE=`date --date=yesterday +%Y%m%d`


Report •

#3
April 18, 2011 at 23:29:40
That's very good! I didn't know that. According to the date man page the option is:

--date=STRING

You used yesterday for STRING. I did some investigating and tomorrow, day (same as tomorrow), week, month, and year work. Also, using strings like "last year" works. I wonder what other STRINGs will work.



Report •

Related Solutions

#4
April 19, 2011 at 08:31:06
I had also looked at the man page for date, but wasn't sure what was expected for the STRING. A friend found "yesterday" would work.

Report •

Ask Question