I am trying to write a command that will keep only the last 2 backups and delete the remaining directories.

directory path = /apps/

Below are the directories and here I would like to keep only

  • source
  • source_2020-01-13
  • source_2019-12-09

directories and delete the old ones. This script will run across 100+ servers using cron.

Here problem is, in find command I wont be able to add mtime to delete old directories - why because backup directories timestamp will not be same on all servers. Basically the command/script should keep the last two backup directories that is with source_YYYY_MM_DD name and delete the remaining ones.

Can someone please assist?

Note : Source_YYYY_MM_DD are the backup directories.

drwx------ 11 root   root   4096 Jul 22  2019 source_2019-07-22
drwx------ 11 root   root   4096 Jul 29  2019 source_2019-07-29
drwx------ 11 root   root   4096 Aug  5  2019 source_2019-08-05
drwx------ 11 root   root   4096 Aug 14  2019 source_2019-08-14
drwx------ 11 root   root   4096 Oct 14  2019 source_2019-10-14
drwx------ 11 root   root   4096 Dec  9 03:59 source_2019-12-09
drwx------ 11 root   root   4096 Jan 13 05:20 source_2020-01-13
drwxr-x--- 12 root   root   4096 Apr 21 09:11 source

2 Answers 2

ls -d1 /apps/source_20??-??-??/ | head -n -2 | xargs rm -rf

ls -d1 /apps/source_20??-??-??/ will list only matching directories in sorted order,
head -n -2 will take out the last two entries and
xargs rm -rf will then delete the directories.

  • Thank you - This command is reliable and deleted the directories as i need
    – Surendar
    Apr 28, 2020 at 9:56
find /apps/ -type d -not -name source -name "source*" -print | sort | head -n -2 | xargs rm -rfv

find apps/ -type d -not -name source -name "source*" -print will find all backup directories making sure the source is not picked up by the find command.

sort will sort, making sure the most recent ones comes last. This is not based on modification times, rather the directory name.

head -n -2 gets all dirs expect the last 2 backup dirs.

xargs rm -rfv deletes the all the backup directories expect the last 2 filtered by the previous command.

(Caution: If you directory names contain spaces, this command will not work. Always test first creating fake directories and trying this command.)

  • Thank you!! Will give it a try and let you know the results
    – Surendar
    Apr 28, 2020 at 9:21
  • Hi - i have tried the command shared under a test directory but it deleted all the "source_" backup directories and didn't deleted source directory alone. find /apps/test/ -type d -not -name source -name "source*" -print | sort | head -n -2 | xargs rm -rfv
    – Surendar
    Apr 28, 2020 at 9:38
  • Can you please assist further?
    – Surendar
    Apr 28, 2020 at 9:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .