Remove files older than X days
Any Linux user or administrator will have had files they need to delete that are no longer needed after a certain amount of time has elapsed. I’ve certainly had to delete various files and logs that are taking up unnecessary space on my servers so I found a way to remove them. I run this every day via a cron job to do the necessary cleanup.
Below is the command that I use to delete files older than X days
find /path/to/folder -mindepth 1 -mtime +30 -delete
||path to the folder where I want to do the cleanup.|
||process files and folders below the given folder. Increasing this number skips that many folders.|
||number of days this file was last accessed. In this case, only return list of files that have not been accessed in the last 30 days.|
||delete the returned file list.|
You can also remove the
-delete parameter and replace it with
-exec to run some other commands such as gzipping the files and backing it up on a remote server. However in this case I just needed to delete the files.
You can also add the
-type parameter to further restrict the type of items that get deleted.
-type accepts the following options. Without the
-type parameter, anything that is returned from the above command gets deleted.
|b||block (buffered) special.|
|c||character (unbuffered) special.|
|d||directory (commonly used).|
|p||named pipe (FIFO).|
|f||regular file (commonly used).|
Hope this helps someone. Happy Linux-ing!!!