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
where
parameter | meaning |
---|---|
/path/to/folder |
path to the folder where I want to do the cleanup. |
mindepth 1 |
process files and folders below the given folder. Increasing this number skips that many folders. |
mtime +30 |
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 |
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.
-type option |
meaning |
---|---|
b | block (buffered) special. |
c | character (unbuffered) special. |
d | directory (commonly used). |
p | named pipe (FIFO). |
f | regular file (commonly used). |
l | symbolic links. |
s | socket. |
Hope this helps someone. Happy Linux-ing!!!