Hi Dude, this article will simply describe about script linux delete folder or file older than x days. I have directories
named as:
2012-12-12
2012-10-12
2012-08-08
How would delete the directories that are older than 10 days with a bash shell script? This will do it recursively for you:
Delete Folder Older Than X Days
Here is simple command.
find /path/to/base/dir/* -type d -ctime +10 -exec rm -rf {} \;
Explanation:
find
: the unix command for finding files / directories / links etc./path/to/base/dir
: the directory to start your search in.-type d
: only find directories-ctime +10
: only consider the ones with modification time older than 10 days-exec ... \;
: for each such result found, do the following command in...
rm -rf {}
: recursively force remove the directory; the{}
part is where the find result gets substituted into from the previous part.
Alternatively, use:
find /path/to/base/dir/* -type d -ctime +10 | xargs rm -rf
Which is a bit more efficient, because it amounts to:
rm -rf dir1 dir2 dir3 ...
as opposed to:
rm -rf dir1; rm -rf dir2; rm -rf dir3; ...
as in the -exec
method.
With modern versions of find
, you can replace the ;
with +
and it will do the equivalent of the xargs
call for you, passing as many files as will fit on each exec system call:
find . -type d -ctime +10 -exec rm -rf {} +
Delete File Older Than X Days
Next, how to method to delete old file?
For example, i have web with code igniter framework. I want to clear ci_session file that dumping to /tmp file.
user@server01 ~# ls -al /tmp/
-rw------- 1 user user 86 Sep 26 22:14 ci_sessionc7a2272efaa08e4bc16
-rw------- 1 user user 86 Sep 27 01:32 ci_sessionc7a2298b92dd8562344
-rw------- 1 user user 86 Sep 26 12:54 ci_sessionc7a2dca33a348890618
-rw------- 1 user user 34 Sep 27 00:37 ci_sessionc7a3fd9ef972a0921fd
...
...
Here is simple way to do it.
find /tmp/ -type f -name 'ci_session*' -ctime +0 -exec rm -rf {} \;
or
find /tmp/ -type f -name 'ci_session*' -exec rm -rf {} \;
That is simple tips to linux script delete folder and file older than x days. That command run in linux/unix. What if we wanti delete file folder older than x day in windows? Here is the article.
May be it’s helpful, please feel free to leave a comment if you have any questions and I’ll appreciate it.
source : https://stackoverflow.com/questions/13868821/shell-script-to-delete-directories-older-than-n-days