How do I make "find" exclude the folder it searches in?
I'm running the following command:
find /var/www/html/content/processing -type d -mtime +1 -exec rm -rf {} \;
I would like to delete all the folders under the processing
folder (the processing folder should never be deleted).
The command is deleting the processing
folder as well. How do I limit the script to delete only the folders under that folder?
The easiest way would be to just add -mindepth 1
, which will skip the first depth hierarchy and thus leave out your parent directory.
Also, you don't need an extra -exec
call to rm
, you can just delete
the folders directly if they're empty.
find /var/www/html/content/processing -mindepth 1 -type d -mtime +1 -delete
If they're not empty:
find /var/www/html/content/processing -mindepth 1 -type d -mtime +1 -exec rm -rf {} \;
If you're lazy you can also have a wildcard expanded. Since *
doesn't include the current directory by default (unless dotglob
is set), you could also do:
find /var/www/html/content/processing/* -type d -mtime +1 -delete
However, this would also not include hidden folders, again due to the dotglob
option.
The problem is that find returns the current directory (.) along with the other directories, so it deletes the processing folder as well as the subdirectories. A quick way to get around that would be to append the option
-not -name .
which stops find from outputting the current directory, and in turn stops it from being deleted.
That would work if you were running the command within the processing directory, so to allow for the fact that you are using an absolute path:
-not -name /var/www/html/content/processing
And the whole command would be:
find /var/www/html/content/processing -type d -mtime +1 -not -name /var/www/html/content/processing -exec rm -rf {} \;
Already answered, still I would like to list another approach.
find /var/www/html/content/processing -mindepth 1 -maxdepth 1 -type d
This will exclude top directory (and also sub directories), and now you can apply whatever command that we want to apply over it.
>> Options:
-mindepth 1 : To exclude root directory
-maxdepth 1 : To avoid parsing sub directories. (For particular scenario as questioned, you don't need this).
-type d : List only directory types. This option should come after mindepth maxdepth uses.