0

I have to delete oldest directory. But, two of directories does not have to be "included" in this action.

So, directory content looks like this:

[root@myserver backup]# ls -la
total 84
drwxr-xr-x 21 root root 4096 Jun 18 04:10 .
drwxr-xr-x 15 root root 4096 Dec 30 11:42 ..
drwxr-xr-x  9 root root 4096 Jan 11 07:25 2013
drwxr-xr-x 13 root root 4096 Jun  4 08:01 2014
drwxr-xr-x  2 root root 4096 Jun 12 04:20 2014-06-12
drwxr-xr-x  2 root root 4096 Jun 13 04:20 2014-06-13
drwxr-xr-x  2 root root 4096 Jun 14 04:20 2014-06-14
drwxr-xr-x  2 root root 4096 Jun 15 04:20 2014-06-15
drwxr-xr-x  2 root root 4096 Jun 16 04:20 2014-06-16
drwxr-xr-x  2 root root 4096 Jun 17 04:20 2014-06-17
drwxr-xr-x  2 root root 4096 Jun 18 04:20 2014-06-18
[root@myserver backup]# 

In this case directory 2014-06-12 have to be deleted, and directories 2013 and 2014 should not be deleted.

I tried by executing next command:

rm -f 'ls -l | grep 2014\- | head -1'

... but it does not deletes anything.

Can you help me how to achieve this?

Thank you in advance!

  • rm -f on its own won't delete a directory. Try the above with rm -rf. – MadHatter Jun 18 '14 at 7:55
2

This command works regardless of the directories' names.
To remove the third oldest directory:
ls --sort t -l | grep -v total | awk '{print $9}' | head -n -2 | tail -1 | xargs rm -rf

  • Nope, I tried with ls --sort t -l /backup | grep -v total | awk '{print $9}' | head -n -1 | tail -1 | xargs rm -rf, it deletes only if I'm in directory /backup. Can you help me with this please? – user48058 Jun 23 '14 at 10:22
  • Maybe just cd before executing it? – psimon Jun 23 '14 at 12:15
  • huh, cd... what in case that cron have to execute it? – user48058 Jun 23 '14 at 13:52
  • Then write a small script that cds before executing the above line and run that script from cron. – psimon Jun 23 '14 at 17:37
1

Try this:

ls -1tr | grep 2014\- | head -1 | xargs rm -rf
  • Why -l? That'll pull in a lot of files with odd names, like drwxr-xr-x, 2, and root. – MadHatter Jun 18 '14 at 8:00
  • -l is just list more information, i rarely use ls, i use ll instead of ls. But some of linux version don't support it. -l is just a personal habbit – Desmond Ho Jun 18 '14 at 8:05
  • Thanks! One more question: what if directories are stored in directory /backup, and I have to execute command from some other directory (or cron have to execute it)? – user48058 Jun 18 '14 at 8:11
  • you may put the path after the ls / ll e.g. ls -l /backup | <other command> – Desmond Ho Jun 18 '14 at 8:14
  • This doesn't work as written the output of ls -l when passed to rm can produce unexpected results and failures. @MadHatter Why didn't you downvote this obviously poor and possibly dangerous answer ? – user9517 Jun 18 '14 at 8:23

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.