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
- Best AI tools for Software Engineers - November 4, 2024
- Installing Jupyter: Get up and running on your computer - November 2, 2024
- An Introduction of SymOps by SymOps.com - October 30, 2024