I want to delete directories only if they have not changed in the last N days. And by changed I mean contain any files that are more recent than N.

I constructed something similar / found this but it doesn't do exactly what i was looking for.

  • Welcome to Unix & Linux. :-) In what way isn't the other one not doing what you want? (Please help us help you!) ;-)*
    – Fabby
    Nov 6, 2018 at 18:34
  • 1
    what about files in subdirectories of the current directory? Do they count towards N?
    – Jeff Schaller
    Nov 6, 2018 at 18:35
  • @Fabby well best I can tell the first one at that link deletes all files older than 10 days. And the second one deletes all directories who's modification times are older 10 than 10 days. Neither of those is evaluating the contents of the directory only removing anything if all the files in the directory are older than 10 days
    – Ryan
    Nov 6, 2018 at 20:06
  • If any of the answers solved your problem, please accept it by clicking the checkmark next to it. Thank you!
    – Jeff Schaller
    Nov 18, 2018 at 13:27

2 Answers 2


I would loop over the directories in question (here, every subdirectory of the current directory) and count the number of lines that find outputs; if that number is zero, then remove the directory. The find command simply asks for files in the given directory that are less than "N" days old (modified in the past "N" days).

for dir in */
  count=$(find "$dir" -type f -mtime -"$N" -print | wc -l)
  [ "$count" -eq 0 ] && echo rm -r -- "$dir"

Remove the echo if the results look correct.

  • I think this might work.
    – Ryan
    Nov 6, 2018 at 20:22

My idea is like this:

 touch -d "4 days ago" .reference_file  
 for dir in */  
   [ $dir -ot .reference_file ] && rm -rf "$dir"  

First, we create a file .reference_file, with create date set as "4 days ago".

Then, for all directories in this working dir we check that its modification time is older ( -ot operator) than modification time of .reference_file.

If is - we remove that directory by rm -rf $dir

Each time we run this script, modification date for .reference_file will be updated to be always 4 days before now.

You must log in to answer this question.

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