Shell Script : Find Files Older X Days And Ask User To Delete

Script that find files older X days and ask user to delete them. Useful for administrator, if needed quickly find old files and delete required files. Script will interactively ask user before deleting the older files.

more shell scripts

Shell Script


#we check for parameters
#Directory is requirede parameter, to avoid deleting from any other folders

if [ $# -eq 0 ]; then

echo "`basename $0` "

echo "Script will delete file folders older than inside "

echo "If no days inputed, will use 7 days as default"


#We save variables

#check if user input days
if [ x"$2" = "x" ]; then

#if user didn't input days, we will use default value




#this will create list of folders older that X days. We use command find to find them, and set maxdepth
# to 1, we don't need recursively find all folders
dirlist=`find $DIR -maxdepth 1 -type d -mtime +$DAYS`

#now we will process each folder
for dir in ${dirlist}


#this will check if user have read and write permissions
if [ ! -r ${dir} -o ! -w ${dir} ]; then

#if no permissions just warn, without try to delete
echo "Access denied to folder ${dir}"


#if we have permissions – we ask user if really delete
read -p "Delete folder ${dir} and all subfolders? [y/n]" confirm

#check if user confirm deleting
if [ "$confirm" = "y" ]; then

#if user confirm – rm command to delete
rm -rf ${dir}




#same as with directories we do with files
#we get list
filelist=`find $DIR -maxdepth 1 -type f -mtime +$DAYS`

#proceed with every file
for file in ${filelist}


#we check permissions
if [ ! -r "${file}" -o ! -w "${file}" ]; then

echo "Access denied to file ${file}"


#if we have permissions we ask about confirmation
read -p "Delete file ${file}? [y/n]" confirm

if [ "$confirm" = "y" ]; then

#if confirmed – we delete file.
rm -rf ${file}





Server1:~/$ ./ /home/yevhen/Downloads 7

Delete folder /home/yevhen/Downloads/CENTOS and all subfolders? [y/n]n

Delete folder /home/yevhen/Downloads/TFTP and all subfolders? [y/n]y

Delete file /home/yevhen/Downloads/Oracle_Solaris_Studio.certificate.pem? [y/n]^C

Server1:~/$ ./ /home/yevhen/Downloads 7

Delete folder /home/yevhen/Downloads/CENTOS and all subfolders? [y/n]n

Delete file /home/yevhen/Downloads/Oracle_Solaris_Studio.certificate.pem? [y/n]n

Delete file /home/yevhen/Downloads/sol-11_1-text-x86.iso? [y/n]^C

Bobbin Zachariah 9:25 am

About Bobbin Zachariah

Founder of LinOxide, passionate lover of Linux and technology writer. Started his career in Linux / Opensource from 2000. Love traveling, blogging and listening music. Reach Bobbin Zachariah about me page and google plus page.

Author Archive Page

Have anything to say?

Your email address will not be published. Required fields are marked *

All comments are subject to moderation.