保留最新N份备份目录脚本
如下所示,在/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
*************** 当你发现自己的才华撑不起野心时,就请安静下来学习吧!***************