rajeshkumar created the topic: Create a script haven’t been accessed for a week, then delete them
Create a script for a cronjob that checks a special directory for files with the extension .tmp that haven’t been accessed for a week, then delete them. Also remove all empty directories.
#!/bin/bash
usage()
{
echo "Usage: $0 [-d Valid Directory] [-e Valid File extension] [-a Access time in a day]" 1>&2;
exit 1;
}
while getopts ":d:e:a:" o; do
case "${o}" in
d)
d=${OPTARG}
if [ ! -d "$d" ]; then
echo "Directory $d not found"
usage
fi
;;
e)
e=${OPTARG}
echo "Passed file extension is $e"
;;
a)
a=${OPTARG}
echo "Passed number of days for access is $a"
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
# for Debug for output
echo "Directory is $d"
echo "File extension is $e"
echo "Accessed time is $a"
# Based on Inputs, this will find the specified file and delete it found accessed according to parameters
#find $d -iname "*$e" -atime -$a -type f -print0
#find /root/raj -iname "*.txt" -atime -1 -type f -print0
find $d -iname "*$e" -atime -$a -type f -print0 | xargs -0 rm -rf
# This can be used as well but xargs would be faster for large file sets.
# find $d -iname "*$e" -atime -$e -type f | exec rm {} \;
# To Remove the empty directory
find $d -type d -empty -exec rmdir {} \;
if [ -z "${d}" ] || [ -z "${e}" ] || [ -z "${a}" ]; then
usage
fi
Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals