I have written the following code to delete files older than 7 days, followed by deleting empty directories older than 7 days.

deleting files

find "$CDIR" ! -type d -mtime +7 -exec sh -c '

        for pathname do

            if ! rm -fv "$pathname"; then



        done' sh {} +

deleting directories

find "$CDIR" -type d -empty -mtime +7 -exec sh -c '

        for pathname do

            if ! rmdir -v "$pathname"; then 



        done' sh {} +`

But, when I delete the files inside a dir, the mtime of the dir is changing, so concerned empty directories are not getting deleted. What is the best way to overcome this.?


2 Answers 2


With zsh (and GNU find or compatible for -delete):

cd -P -- "$CDIR" || exit
find . -mtime +6 ! -type d -delete
(($#empty_old_dirs == 0)) || rmdir -- $empty_old_dirs

Note that -mtime and zsh's m glob qualifier works with ages in integer (rounded down) number of days. -mtime -6 is for the age being strictly less than 6, -mtime 6 is for that age being 6 (so in effect, between 6 and 7 days) and -mtime +6 for that age strictly greater than 6, so 7 days and above.

So for files that are more than 7 days old, you want -mtime +6, not -mtime +7 (at least with POSIX compliant find implementations, not all are but GNU's one is in that regard).


You can first add the 7 day old empty directories to a temp file and run your file removal. Then search for empty directories and check against the file.

dirs_mtime7=$(mktemp) ## Create a temp file. 
find "$CDIR" -type d -mtime +7 >> "${dirs_mtime7}" 
## File deletion find command goes HERE ...
while IFS= read -r -d '' a; do         
 grep -q -F -f "${dirs_mtime7}" <<< "${a}" && rmdir -v "${a}" 
done < <(find "$CDIR" -type d -empty -print0)

Since they are only getting older you can just add to the temp file the new 7 day + directories. Create the dirs_mtime7 directory only once and add to it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .