Bash scripting: deleting the oldest directory

I want to find the oldest directory (inside the directory) and delete it. I am using the following:

rm -R $(ls -1t | tail -1) 

ls -1t | tail -1 ls -1t | tail -1 really gives me the oldest directory, the problem is that it does not delete the directory and that it also lists files.

How can i fix this?

+6
bash directory file-io delete-directory
source share
4 answers

This is not very, but it works:

 rm -R $(ls -lt | grep '^d' | tail -1 | tr " " "\n" | tail -1) 
+3
source share
 rm -R "$(find . -maxdepth 1 -type d -printf '% T@ \t%p\n' | sort -r | tail -n 1 | sed 's/[0-9]*\.[0-9]*\t//')" 

It also works with a directory whose name contains spaces, tabs, or begins with a "-".

+5
source share
 rm -R $(ls -tl | grep '^d' | tail -1 | cut -d' ' -f8) 
0
source share

 find directory_name -type d -printf "%TY%Tm%Td%TH%TM%TS %p\n" | sort -nr | tail -1 | cut -d" " -f2 | xargs -n1 echo rm -Rf 
You should remove the echo before the rm if it produces the right results
0
source share

All Articles