I have directories named as:
2012-12-12
2012-10-12
2012-08-08
How would I delete the directories that are older than 10 days with a bash shell script?
I have directories named as:
2012-12-12
2012-10-12
2012-08-08
How would I delete the directories that are older than 10 days with a bash shell script?
find
supports-delete
operation, so:I think there's a catch that the files need to be 10+ days older too. Haven't tried, someone may confirm in comments.
The most voted solution here is missing
-maxdepth 0
so it will callrm -rf
for every subdirectory, after deleting it. That doesn't make sense, so I suggest:The
-delete
solution above doesn't use-maxdepth 0
becausefind
would complain the dir is not empty. Instead, it implies-depth
and deletes from the bottom up.OR
Updated, faster version of it:
This will do it recursively for you:
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:
Which is a bit more efficient, because it amounts to:
as opposed to:
as in the
-exec
method.With modern versions of
find
, you can replace the;
with+
and it will do the equivalent of thexargs
call for you, passing as many files as will fit on each exec system call:I was struggling to get this right using the scripts provided above and some other scripts especially when files and folder names had newline or spaces.
Finally stumbled on tmpreaper and it has been worked pretty well for us so far.
Original Source link
Has features like test, which checks the directories recursively and lists them. Ability to delete symlinks, files or directories and also the protection mode for a certain pattern while deleting
If you want to delete all subdirectories under
/path/to/base
, for examplebut you don't want to delete the root
/path/to/base
, you have to add-mindepth 1
and-maxdepth 1
options, which will access only the subdirectories under/path/to/base
-mindepth 1
excludes the root/path/to/base
from the matches.-maxdepth 1
will ONLY match subdirectories immediately under/path/to/base
such as/path/to/base/dir1
,/path/to/base/dir2
and/path/to/base/dir3
but it will not list subdirectories of these in a recursive manner. So these example subdirectories will not be listed:and so forth.
So , to delete all the sub-directories under
/path/to/base
which are older than 10 days;