Friday, March 8, 2013

Delete files older than ‘N’ no of days.

Here I try to delete “.gz” files that are older than ‘n’ days.
However I make sure at least one file retain in the system after delete else no delete .


#!/bin/sh
# Author : SanjeewaF(21-02-2013)
#This file is to delete gzip files afterX no of days.
#Please only run them needed .


export PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
CFG_FILE_PATH=/share/backups/reports/
FILE_TYPE=*.gz

NOW=$(date +"%Y-%m-%dT%H%M")
CFG_CUTTOFF_NO_DATES=45

if [ -w "$CFG_FILE_PATH" ]
then
noDeL=`find $CFG_FILE_PATH$FILE_TYPE -maxdepth 1 -nowarn -mtime +$CFG_CUTTOFF_NO_DATES 2>/dev/null | wc -l`
noExt=`find $CFG_FILE_PATH$FILE_TYPE -maxdepth 1 -nowarn 2>/dev/null | wc -l`

#echo "find $CFG_FILE_PATH$FILE_TYPE -maxdepth 1 -nowarn -mtime +$CFG_CUTTOFF_NO_DATES 2>/dev/null | wc -l"
#echo "find $CFG_FILE_PATH$FILE_TYPE -maxdepth 1 -nowarn 2>/dev/null | wc -l"

if [ $noDeL -ne 0 ] && [ $noExt -gt $noDeL ]
then

  echo "Deleting files older than $CFG_CUTTOFF_NO_DATES"
  find $CFG_FILE_PATH$FILE_TYPE -maxdepth 1 -nowarn -mtime +$CFG_CUTTOFF_NO_DATES -print


find $CFG_FILE_PATH$FILE_TYPE -maxdepth 1 -nowarn -mtime +$CFG_CUTTOFF_NO_DATES -print | xargs rm


else
  echo "unable delete all or no files del=$noDeL all=$noExt"
exit 1
fi
else
  echo "unable to find the writable directory $CFG_FILE_PATH"
fi

No comments:

Post a Comment