Shell Script to Find Files Older X Days and Delete

more shell scripts
Useful for administrator, if needed quickly find old files and delete required files. This shell script will find files that are older by X days then confirm user to delete them.

The script will interactively ask user before deleting the older files or directories.

Shell Script to delete File by X Days

#!/bin/bash

#we check for parameters
#Directory is required 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"

fi

#We save variables
DIR=$1

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

#if user didn't input days, we will use default value
DAYS="7"

else

DAYS="$2"

fi

#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}

do

#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}"

else

#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}

fi

fi

done

#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}

do

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

echo "Access denied to file ${file}"

else

#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}

fi

fi

done

Script Output

In the following script we are deleting files and directories which are 7 days old:

Server1:~/$ ./delete_xdays.sh /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:~/$ ./delete_xdays.sh /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

Comments

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

All comments are subject to moderation.