Operating System - HP-UX
1828944 Members
2442 Online
109986 Solutions
New Discussion

Shell Script to Archive Files more than 7 Days Old

 
SOLVED
Go to solution
John Felgendreger
Occasional Contributor

Shell Script to Archive Files more than 7 Days Old

I have a requirement to runs a script daily to archive any file greater than 7 days old. The files will be created with a date in their name. e.g. file SIA1.2000090809 would have been created on September 8th 2000. I want to move that file to an archive directory on September 15th.

Does anyone have a canned script that can accomplish the task?

Thanks.

John Felgendreger
4 REPLIES 4
John Palmer
Honored Contributor

Re: Shell Script to Archive Files more than 7 Days Old

Probably your easiest option is to use the 'mtime' argument to 'find' rather than extracting the date from the filename itself.

cd
find . -mtime +6 -exec mv {} \;

Will move files 7 days old and older.
James R. Ferguson
Acclaimed Contributor

Re: Shell Script to Archive Files more than 7 Days Old

John:

You can use:

# cd /mydirectory
# find . -mtime +7 | cpio -pdxm /myarchive

...JRF...
Kofi ARTHIABAH
Honored Contributor
Solution

Re: Shell Script to Archive Files more than 7 Days Old

might this be something you are looking for...

#!/bin/sh
# Assumptions: 1. that you already have the files created SIA*
# 2. That this script will be run once a week (eg. from the cron)
#

BASE_DIR=/archive
SOURCE_DIR=/source
NUMERIC_DATE=`date +%Y%m%d`
DAY_OF_WEEK=`date +%u`
DAY_TO_RUN=7 # Set day to run to Sunday, ie. run this only on Sundays

# BASE_DIR is the base archive directory ( change to whatever you want your archive files to be stored in )
# SOURCE_DIR is where your files SIA* are found.

if [ $DAY_OF_WEEK -ne $DAY_TO_RUN ] ; then

if [ ! -d $BASE_DIR/$NUMERIC_DATE ] ; then

mkdir $BASE_DIR/$NUMERIC_DATE # if archive directory for this week does not exist then
# create it
fi

find $SOURCE -name "SIA*" -mtime +6 -exec mv {} $BASE_DIR/$NUMERIC_DATE/ \;

# look for all files with starting with the name SIA that are older than 6 days
# and move them to the corresponding directory

else

echo " Sorry nothing to do today - this has been set to run only on the $DAY_TO_RUN day"

fi

nothing wrong with me that a few lines of code cannot fix!
James R. Ferguson
Acclaimed Contributor

Re: Shell Script to Archive Files more than 7 Days Old

John:

I might add that if you are interested in preserving the last access times of the files in question, add the -a option to the cpio. Thus:

# cd /mydirectory
# find . -mtime +7 | cpio -padxm /myarchive

...JRF...