How to list or remove file which is older then N days


If you are trying to get a list of files or directory which is older then "N" days you should check this script. There is an easy way to get this information with the find command. Find command mtime option will show us the files which older than "N" days. Also, the script will show us the file's  last modified date.

Usage:

To Define Action = "-a list|remove"
To Define Days = "-d NumberOfDays"
To Define File or Directory search = " -t f|d"
To Define Path = "-p FilePath"'

Example-1:This  example will list files  which  are  older then 30  days.
#./NdaysOlder.sh  -a  list  -t f -p  /tmp/  -d 30

Example-2:This  example will list files  which  are  older then 30  days.
#./NdaysOlder.sh  -a  list  -t d -p  /tmp/  -d 10


#!/bin/bash
RUN_LS (){
echo "File older then $Days under $Path:"
find $Path -type $Type -mtime +$Days -exec stat -c "%n %y" {} \;|column -t
}

while getopts "a:d:p:t:" option; do
case $option in
d ) Days=$OPTARG
;;
p ) Path=$OPTARG
;;
t ) Type=$OPTARG
;;
a ) Act=$OPTARG
;;
esac
done
if [ -z "$Days" ] || [ -z "$Type" ] || [ -z "$Path" ]
then
echo 'Missing Argument!Please use this format:
To Define Action = "-a list|remove"
To Define Days = "-d NumberOfDays"
To Define File or Directory = " -t f|d"
To Define Path = "-p FilePath"'
else
if [ $Act == "list" ]
then
RUN_LS
elif [ $Act == "remove"]
then
RUN_RM
else
echo "No option Defined.Please chose list or remove"
fi
fi

 

Tagged In:

I'm a IT Infrastructure and Operations Architect with extensive experience and administration skills and works for Turk Telekom. I provide hardware and software support for the IT Infrastructure and Operations tasks.

205 Total Posts
Follow Me