# emerge life

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:


Are you sure you want to continue? [y/n]

And here’s the script:

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
if [[ $REPLY =~ ^[Yy]$ ]]
		find "$2" -mtime +"$1" -delete
        echo -e '\nDone!'
        echo -e '\nAborted!'

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 -delete with 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! :)


I don't have a commenting system on my blog since there's no good solutions that works without JavaScript, is user friendly and respects both the users freedom and privacy. So for now, all feedback and hellos can be done via either e-mail, XMPP or Mastodon.