Delete all directories except the most recent

I'd like to write a script that delete all the directories (that are not empty) from a directory, but keep the most recent one. Is that possible, and how?

0

2 Answers

Here is a way to do this using find.

find -type d ! -wholename $(find -type d -printf '%T+ %p\n' | sort -r | head -1 | cut -d" " -f2) ! -wholename "." -exec rm -r {} +

Command breakdown:

  • find -type d the first part tells find to search for directories only
  • ! -wholename exclude hits with the following complete name. The following part (between $()) is evaluated and used as file name here
    • $(find -type d -printf '%T+ %p\n' | print timestamps for directories
    • sort -r | sort them newest to oldest
    • head -1 | take only the first line (newest directory)
    • cut -d" " -f2) remove the timestamp from the output
  • ! -wholename "." exclude hits with the complete name .. You cannot remove the directory, your currently working in.
  • -exec rm -r {} + remove the matching files.

You should run the command without the last part (-exec rm -r {} +) first, to see which directories will be removed.


Example:

directory content:

Aug 4 14:38 bar/
Aug 4 14:38 bla
Aug 4 14:38 foo/
Aug 4 14:41 foobar/

running command:

find -type d ! -wholename $(find -type d -printf '%T+ %p\n' | sort -r | head -1 | cut -d" " -f2) ! -wholename "." -exec rm -r {} +

resulting directory content:

Aug 4 14:38 bla
Aug 4 14:41 foobar/

note that bla is a file and not a directory. So it will not be removed.

I found an answer, and leave it here, it might be useful for other users :

cd /path/to
rm -r `ls -t | awk 'NR>1'`
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like