Bash scripting: Deleting the oldest directory
Asked Answered
R

4

6

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?

Roadblock answered 31/8, 2010 at 18:59 Comment(0)
H
3

This is not pretty but it works:

rm -R $(ls -lt | grep '^d' | tail -1  | tr " " "\n" | tail -1)
Heer answered 31/8, 2010 at 19:5 Comment(1)
Be careful: it does not work if the directory name contains spaces.Gimble
G
8
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 "-".

Gimble answered 31/8, 2010 at 19:42 Comment(0)
H
3

This is not pretty but it works:

rm -R $(ls -lt | grep '^d' | tail -1  | tr " " "\n" | tail -1)
Heer answered 31/8, 2010 at 19:5 Comment(1)
Be careful: it does not work if the directory name contains spaces.Gimble
M
0
rm -R $(ls -tl | grep '^d' | tail -1 | cut -d' ' -f8)
Mulligatawny answered 31/8, 2010 at 19:5 Comment(0)
G
0


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
Gillette answered 31/8, 2010 at 19:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.