RichR
RichR

Reputation: 425

Remove directories when find uses wildcard in middle of path

I need to remove directories (and their contents) in a clean-up routine executed by cron. I'm not sure if I am approaching this correctly. To test to see what would be removed, I substituted echo rather than running and rm -rf. The issue may be that my wildcard is in the middle of a path....??

#!/bin/bash

dirsPATH="/images/*/03_processed"

find $dirsPATH -type d -mtime +2 -maxdepth 2 -exec echo {} \;

or

for i in $(find $dirsPATH -type d -mtime +2)
do
   echo $i
done

I don't want to remove the "03_processed" directories, I want to remove the contents of those directories - however when I run either of these, the output includes /images/xxxx/03_processed

/images/aaaa/03_processed
/images/aaaa/03_processed/761010184884
/images/aaaa/03_processed/79171833116
/images/aaaa/03_processed/873705734964
/images/aaaa/03_processed/997297772672
/images/bbbb/03_processed
/images/bbbb/03_processed

I've tried with a trailing "/" in the variable definition, and also in the command using "$dirsPATH/"...

Any ideas would be appreciated - thanks

Upvotes: 2

Views: 2522

Answers (2)

ghoti
ghoti

Reputation: 46896

If your goal is to remove the contents of directories, testing with echo was a very good idea.

Your first examples, however, use find commands which will necessarily include those directories.

One solution might be to use -mindepth, as hek2mgl suggests. Another might be just to use bash's own pathname expansion.

echo /images/*/03_processed/*/

If this list matches what you think should be deleted (notwithstanding -mtime), use that for find:

find /images/*/03_processed/*/ -mtime +2 -maxdepth 0 -type d -ls

And of course, when you're ready, replace -ls with -exec rm -rfv {} \; or the like.

NOTE the -mtime +2 limit is being applied in all these cases to THE DIRECTORY, not its contents. It is possible that files could be updated within these directories, or files or directories created in contained directories, without the last-modified time being affected on the parent directory. To demonstrate this:

$ mkdir foo; stat foo | grep ^Mod
Modify: 2016-01-12 11:58:37.219228265 -0500
$ sleep 5; mkdir foo/bar; stat foo | grep ^Mod
Modify: 2016-01-12 11:58:42.581329442 -0500
$ sleep 5; mkdir foo/bar/baz; stat foo | grep ^Mod
Modify: 2016-01-12 11:58:42.581329442 -0500
$ 

Note that the final directory creation (baz) did not affect the modified time of foo.

Upvotes: 3

hek2mgl
hek2mgl

Reputation: 158260

Use the -mindepth option of find:

find $dirsPATH -mindepth 1 -maxdepth 2 -type d -mtime +2 -exec echo {} \;

Btw, if you just test which files will be found before actually using the -exec option, simply omit it. Printing the file name is the default behaviour:

find $dirsPATH -mindepth 1 -maxdepth 2 -type d -mtime +2

Upvotes: 1

Related Questions