How to delete files and folders older than N days
There’s a lot of tips and recommendations about how to delete files and folders older than
<N> days on the web, but you can’t as far as I know do it with only one command. And running
rm -rf in the shell without any confirmation feels a bit too risky as well. Because no matter how experienced you are, accidents do happen. :)
That’s why I wrote this little script that let’s you in a safe manner verify both the age and folder before actually doing anything. I named the script
deleteOldFiles.sh and it works by you first specifying the days followed by the path.
$ deleteOldFiles.sh 3 Nextcloud/tmp These are the files and/or folders that will be deleted: Nextcloud/tmp/2018-07-15-224841_628x482_scrot.png Nextcloud/tmp/IMG_20180719_114053.jpg Nextcloud/tmp/IMG_20180719_172601.jpg Are you sure you want to continue? [y/n]
And here’s the script:
#!/bin/bash set -e set -u files=$(find "$2" -mtime +"$1" -print) printf "\nThese are the files and/or folders that will be deleted:\n\n" printf "$files" printf "\n\n" read -p $'Are you sure you want to continue? [y/n] ' -n 1 -r echo if [[ $REPLY =~ ^[Yy]$ ]] then find "$2" -mtime +"$1" -delete echo -e '\nDone!' else echo -e '\nAborted!' fi
I’m not a programmer in any way, so if you have any feedback about it (good or bad) let me know. :)
July 24, 2018
I got some feedback here and I was told that using the flag
find is a better and more secure way of doing it. So I changed my script to use the
-delete flag as well as adding the feature that it now prints the files and/or folders that’s going to get deleted.
July 24, 2018
I got more feedback! And even a merge request with some further improvements to my script. Thanks! :)