bash scripting question

Charles Steinkuehler charles at steinkuehler.net
Thu Feb 13 20:37:28 CST 2003


Jeremy Fowler wrote:
> First off, you are going to want to put the year first or you will run into
> problems in the future, so just:
> 
> mkdir save`date +%y%m%d`
> 
> Then you can use the -d switch to specify what date you want:
> 
> rm -rf save`date +%y%m%d -d "yesterday"`
> rm -rf save`date +%y%m%d -d "3 days ago"`
> rm -rf save`date +%y%m%d -d "3 months ago"`

With the dates in the proper order (year/month/day, so they sort 
properly), you can also do fun things like keep the 10 most recent files 
(deleting the others):

rm -rf `ls -1 save* | sed '1,10d'`

or for a version that's probably more robust (if you don't have more 
than 10 files):

for FILE in `ls -1 save* | sed '1,10d'` ; do
   rm -rf $FILE
done

And other fun tricks, like deleting everything older than 3 days:

SAVE=save`date +%y%m%d -d "3 days ago"`
for FILE in `ls -1 save* | sed 1,/$SAVE/d` ; do
   rm -rf $FILE
done

All of the above untested...use at your own risk!

Warning:  If you have *LOTS* of matching files (like thousands), your 
list can grow bigger than the shell can deal with.  In this case, you 
can switch to using the find command, coercing it to run the desired 
command(s) on the files one at a time, rather than building a list.  You 
can also pipe the  file list to a temporary file, using that to get 
around the shell's environment size limit, or just use pipes, something 
like:

ls -1 save* | sed '1,10d' | while read FILE ; do
   rm -rf $FILE
done

This avoids ever expanding the file list completely.

Regardless, you can have *LOTS* more fun with your files if they sort 
properly by date, which means year then month then day formatting.

-- 
Charles Steinkuehler
charles at steinkuehler.net




More information about the Kclug mailing list