Sometimes you want to remove old files on a server, like old log files or temporary files created ages ago, that are no longer relevant. Here’s a quick command that lets you do that.
But first, let’s play safe and show you a command to view the files older than X days, so you can review the list first before you launch the delete-command.
$ find . -mtime +180 -print
To break it down: we use find
in the current directory (the dot .
) and list all files with a modification date that’s older than 180 days. After that, we print the files to stdout with the -print
command (which, technically, is obsolete – you can omit that parameter and it’ll still work, but it makes for a clearer example).
To pass an other directory, simply replace the dot:
$ find /to/your/directory -mtime +180 -print
Now, to actually delete the files older than X days, you can use any of these variants. Be careful though, there’s no trashbin or confirmation in this case, once you copy/paste this, it’ll delete everything in your current working directory older than 180 days. ;-)
$ find . -mtime +180 -delete; $ find . -mtime +180 -exec rm -f {} \;
As before, the -mtime
parameter is used to find files older than X. In this case, it’s older than 180 days. You can either use the -delete
parameter to immediately let find delete the files, or you can let any arbitrary command be executed (-exec
) on the found files.
The latter is slightly more complex, but offers more flexibility if want to copy them to a temp directory instead of deleting. In that case, you can swap out the rm
with an mv
.