Tuesday, November 25, 2008

BASH script to delete older files

# BASH Script to find files having Modification time older than 7 days and to remove.
# A provisional confirmation before deletiion has been included
# System files starting with "." in their names are excluded from deletion
# And exclusive files that are specifies in the exclusion list are prevented from being deleted

#!/bin/bash
DIR=/home/hari
LIST=/home/hari/DELETE_LIST
EXCLUSIONS=/home/hari/EXCLUSIONS

# Simply the below command will do it
# find $DIR -type f -mtime +7 | grep ^./ | grep -v -f $EXCLUSIONS -exec rm {} \;
# But for the time being it run on a CONFIRMATION before deleting the files.

#Declaration for CONFIRM()
CONFIRM()
{
echo "Going to remove $1"
echo "Do you want to Continue? -y/n"
read CHOICE
if [ $CHOICE = 'y' ]
then
rm -f $1
elif [ $CHOICE = 'n' ]
then
exit
else
echo Invalid choice
exit
fi
}
# Function FIND_FILES
FIND_FILES()
{
cd $DIR
find -type f -mtime +7 | grep ^./ | grep -v -f $EXCLUSIONS > $LIST
for i in `cat $LIST`
do
CONFIRM $ENTRY
done
}


# Call to main function FIND_FILES()
FIND_FILES
exit

No comments: