0

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 '18 at 18:34
  • 1
    what about files in subdirectories of the current directory? Do they count towards N? – Jeff Schaller Nov 6 '18 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 '18 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 '18 at 13:27
1

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).

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

Remove the echo if the results look correct.

  • I think this might work. – Ryan Nov 6 '18 at 20:22
0

My idea is like this:

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.