Remove files older than x days

I love using cli scripts to make my life easier, both in Linux and Windows. On this site you can see several examples of that, including the use of backup scripts for several systems/applications. Making a script that does this can sometimes give you a headache by having to remove logfiles or accumulated compression files (zip, rar, tar) manually. Below are commands for both Windows and Linux to check the files in a directory and remove them if they are older than a certain amount of time. Very useful to keep your hard disks clean of junkfiles.

As per usual, substitute the options marked in red for your own path and expire days.


find /path/to/directory/ -type f -mtime +3 -exec rm {} \;

This will remove all normal files older than 3 days in the set directory.


forfiles /p c:\path\to\directory\ /m *.* /d –3 /c “cmd /c del @file”

Same thing but on Windows.

I suggest adding this option to the MySQL backup script from a few posts back. This backup script makes a tar file per database, per day. Depending on how many databases you host on the MySQL server you can get to 100’s of files within a few months if you forget to clean the directory manually.

Leave a Reply

Your email address will not be published.