Script to delete except recent 3 File or Folder in Linux

Posted: January 28, 2016 in Delete Except recent 3 backup, Shell Script

Scenario

For my production Environment i want take backup of daily basis under /backup/DB using incremental backup method.

Example:

[root@server1 DB]# pwd
/backup/DB
[root@server1 DB]# ls -lt
total 20
drwxr-xr-x 2 root root 4096 Dec  5 05:29 backup-29-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:27 backup-28-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:25 backup-27-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:22 backup-26-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:21 backup-25-01-2016

From above output i am taking backup daily basis . But after few days my File system got full to avoid this we can delete except recent DB backup. But this i have to do daily or when ever disk full i have take action. Avoid this i am writing small script and scheduling.

Script: clean-old-backup.sh

#!/bin/bash
clear
P=’/backup/DB’
echo “script to Clean up Database”
cd $P
echo -e “\n\tBefore Clean up”
echo “————————————————————”
ls -lt
echo “————————————————————”
ls -t | tail -n +4 | xargs rm -rf
echo -e “\n\tAfter Clean up”
echo “———————————————————–”
ls -lt
echo “———————————————————–”

Run #./clean-old-backup.sh

Output

script to Clean up Database

Before Clean up
————————————————————————–
total 24
drwxr-xr-x 2 root root 4096 Dec  5 05:40 backup-30-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:29 backup-29-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:27 backup-28-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:25 backup-27-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:22 backup-26-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:21 backup-25-01-2016
—————————————————————————

After Clean up
————————————————————————-
total 12
drwxr-xr-x 2 root root 4096 Dec  5 05:40 backup-30-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:29 backup-29-01-2016
drwxr-xr-x 2 root root 4096 Dec  5 05:27 backup-28-01-2016
————————————————————————

[root@server1 ~]# crontab -l
00      20      *       *       *       /bin/bash /root/clean-old-backup.sh

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s