Wednesday, July 8, 2009

Script - Remove files older than 1 day from /root

A quick bash script that I wrote that does the following:

Checks to see if the user is root (good to do with all your scripts if you 'sudo')
finds all files older than 1 day (-ctime +1)
deletes the files
sends an email to 'root' with a small report of the deleted files

(the numb -3 is to calculate the number of files deleted - there are 3 header lines in the report)
(the statement in bold allows you to specify file formats to delete...*.csv in my case...)

------------------------------------------
#!/bin/bash
# rmroottemp.sh
# Written by Andrew Elliott, 20-feb-2009
#

RM_LOG=/root/rmroottemplog.txt
ROOT_UID=0

if [ "$UID" -ne "$ROOT_UID" ]
then
echo "Must be root to run this script!"
exit
fi

cd /root

echo "-----------------------------" > $RM_LOG
echo "Report for files removed from /root" >> $RM_LOG
echo "-----------------------------" >> $RM_LOG

find /root -ctime +1 -maxdepth 1 | grep 'searchtermhere' | while read TEMP1
do
echo "$TEMP1" >> $RM_LOG
rm -rf $TEMP1
done

NUMB=`cat $RM_LOG | wc | cut -c1-8 | sed 's/^[ ]*//'`
NUMB=$(($NUMB - 3))
/bin/mail -s "Root temp file cleanup $NUMB files deleted" root < $RM_LOG
rm -rf $RM_LOG
exit 0
------------------------------------------

No comments:

Post a Comment