3

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?

2

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.

0

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
    It is not a good idea to parse ls, because you may get problems when you have filenames that contain whitespace. It is generally better to use find for this kind of things. – Wayne_Yux Aug 4 '16 at 11:21

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.