Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash scripting: Deleting the oldest directory

I want to look for the oldest directory (inside a directory), and delete it. I am using the following:

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

ls -1t | tail -1 does indeed gives me the oldest directory, the the problem is that it is not deleting the directory, and that it also list files.

How could I please fix that?

like image 297
Jary Avatar asked Aug 31 '10 18:08

Jary


2 Answers

rm -R "$(find . -maxdepth 1 -type d -printf '%T@\t%p\n' | sort -r | tail -n 1 | sed 's/[0-9]*\.[0-9]*\t//')"

This works also with directory whose name contains spaces, tabs or starts with a "-".

like image 110
Giuseppe Cardone Avatar answered Sep 24 '22 11:09

Giuseppe Cardone


This is not pretty but it works:

rm -R $(ls -lt | grep '^d' | tail -1  | tr " " "\n" | tail -1)
like image 21
codaddict Avatar answered Sep 26 '22 11:09

codaddict