I need to write a script for a web server that will clean out files/folders older than 14 days, but keep the last 7 files/directories. I’ve been doing my research so far and here is what I came up with (I know the syntax and commands are incorrect but just so you get an idea):
ls -ldt /data/deployments/product/website.com/*/ | tail -n +8 | xargs find /data/deployments/product/website.com/ -type f -type d -mtime +14 -exec rm -R {} \;
This is my thought process as to how the script should behave (I’m more a windows batch guy):
List the directory contents
If contents is less than or equal to 7, goto END
If contents is > 7 goto CLEAN
:CLEAN
ls -ldt /data/deployments/product/website.com/*/
keep last 7 entries (tail -n +8)
output of that "tail" -> find -type f -type d (both files and directories) -mtime +14 (not older than 14 days) -exec rm -R (delete)
I’ve seen a bunch of examples, using xargs and sed but I just can’t figure out how to put it all together.
remove the
echoif your happy with the output…Explanation (line-by-line):
findin exactly inyour_dirand print seconds_since_Unix_epoch (%T@) and file(/dir)name for each file/dir on a separate linexargspasses on to newfindprocess argument-by-argument (-n1) and usesfnameto represent argument-maxdepth 0limitsfindto justfnameYou could store the minNrOfFiles and the ageLimit in Bash-Variables or pass in to the script with just few changes:
change:
sed '1,'"$minNrOfFiles"'d'and-mtime +"$ageLimit"