如下所示,在/opt/backup下是備份目錄,只需要保留最新的三份備份,在此之前的備份目錄都要刪除。
[root@syslog-ng ~]# cd /opt/backup/ [root@syslog-ng backup]# ls -l total 68 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180626 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180627 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180628 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180629 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180630 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180631 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180701 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180702 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180703 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180704 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180705 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180706 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180707 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180708 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180709 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180710 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180711 [root@syslog-ng backup]# /bin/ls -l |grep "^d" drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180626 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180627 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180628 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180629 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180630 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180631 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180701 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180702 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180703 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180704 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180705 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180706 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180707 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180708 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180709 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180710 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180711 [root@syslog-ng backup]# /bin/ls -l |grep "^d"|awk '{print $9}' 20180626 20180627 20180628 20180629 20180630 20180631 20180701 20180702 20180703 20180704 20180705 20180706 20180707 20180708 20180709 20180710 20180711 [root@syslog-ng backup]# /bin/ls -l |grep "^d"|awk '{print $9}'|wc -l 17 [root@syslog-ng backup]# /usr/bin/expr 17 - 3 14
處理指令碼如下
[root@syslog-ng backup]# cat /opt/del.sh #!/bin/bash cd /opt/backup NUM1=$(/bin/ls -l |grep "^d"|awk '{print $9}'|wc -l) NUM2=$(/usr/bin/expr $NUM1 - 3) /bin/ls -l |grep "^d"|awk '{print $9}'|/bin/sed -n "1,$NUM2 p"|xargs rm -rf
授予指令碼執行許可權
[root@syslog-ng backup]# chmod 755 /opt/del.sh
執行指令碼
[root@syslog-ng backup]# sh /opt/del.sh
執行指令碼後,發現保留下來的備份目錄就行最新的三份了
[root@syslog-ng backup]# ll total 12 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180709 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180710 drwxr-xr-x. 2 root root 4096 Jul 11 14:48 20180711