How to delete files, directory and subdirectory which is older than N days in shell, Unix or Linux

Shell @ Freshers.in

For mostly, logs and other temp files, its a common use case to delete the files older than 30 or 60 days. You can achieve this using this command

find /log_or_temp_location/* -mtime +30 -exec rm {} \;

Here log_or_temp_location , is the directory where you want to do the clean up, in short path of the file. This can be a path of the file or directory or wildcard.
-mtime :  This is needed to specify the number of days file/folder  is old.
+30 : Here it mentions 30 days old.
-exec : This will allows you to send the command , that need to get execute : for example rm.
You need to add {} \ at the end of the statement.
The above command will not work , if you have any contents in the directory.

To force delete all the contents and the directory then 

find /log_or_temp_location/* -mtime +30 -exec rm -rf {} \; 

Some of other similar commands are 

find /log_or_temp_location/* -daystart -mtime +30 -delete

-daystart is some thing like the calendar date. -daystart -mtime 0 gives files that are Zero Days Old,which means  from today

To remove empty directories you can give as 

find /log_or_temp_location/* -empty -type d -delete

You can try the below to do recursively 

find /log_or_temp_location/* -type d -ctime +30 -exec rm -rf {} \;

find: Shell command for finding files and directories.
/path/to/base/dir: The path of the directory to start your search.
-type d: If you need to find only directories
-ctime +30: File or directlry modification time older than 30 days
-exec … \;: For each such result you got , do the following command in .
rm -rf {}: Recursively force t0 remove the directory.
{} : Find result gets substituted into from the previous part.

Author: user

Leave a Reply