Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Create a script haven’t been accessed for a week, then delete them

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

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.

0
Would love your thoughts, please comment.x
()
x