欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

实现自动清除日期目录shell脚本实例代码

程序员文章站 2022-06-16 16:15:23
实现自动清除日期目录shell脚本实例代码 很多时候备份通常会使用到基于日期来创建文件夹,对于这些日期文件夹下面又有很多子文件夹,对于这些日期文件整个移除,通过find结...

实现自动清除日期目录shell脚本实例代码

很多时候备份通常会使用到基于日期来创建文件夹,对于这些日期文件夹下面又有很多子文件夹,对于这些日期文件整个移除,通过find结合rm或者delete显得有些力不从心。本文提供一个简单的小脚本,可以嵌入到其他脚本,也可直接调用,如下文供大家参考。 

1、脚本内容

[root@szdb ~]# more purge_datedir.sh  
#!/bin/bash 
# author: leshami 
# blog : http://blog.csdn.net/leshami 
 
removedir=/log/hotbak/physical 
dt=`date +%y%m%d -d "3 day ago"` 
 
for subdir in `ls $removedir`; 
do 
  if [ "${subdir}" \< "${dt}" ]; 
    then  
    rm -rf $removedir/$subdir >/dev/null 
    echo "the directory $removedir/$subdir has been removed." 
  fi 
done 

2、演示

[root@szdb ~]# ls /log/hotbak/physical 
20141203 20141210 20141217 20141224 20141231 20150107 20150114 20150125 tmp.sh 
20141207 20141214 20141221 20141228 20150104 20150111 20150121 20150128 
 
[root@szdb ~]# ./purge_datedir.sh  
the directory /log/hotbak/physical/20141203 has been removed. 
the directory /log/hotbak/physical/20141207 has been removed. 
the directory /log/hotbak/physical/20141210 has been removed. 
the directory /log/hotbak/physical/20141214 has been removed. 
the directory /log/hotbak/physical/20141217 has been removed. 
the directory /log/hotbak/physical/20141221 has been removed. 
the directory /log/hotbak/physical/20141224 has been removed. 
the directory /log/hotbak/physical/20141228 has been removed. 
the directory /log/hotbak/physical/20141231 has been removed. 
the directory /log/hotbak/physical/20150104 has been removed. 
the directory /log/hotbak/physical/20150107 has been removed. 
the directory /log/hotbak/physical/20150111 has been removed. 
the directory /log/hotbak/physical/20150114 has been removed. 
the directory /log/hotbak/physical/20150121 has been removed. 
 
[root@szdb ~]# ls /log/hotbak/physical 
20150125 20150128  

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!