linux前一天的目录,shell删除前一天的目录并保留月末那天的目录

该博客展示了如何使用Linux shell脚本来自动删除指定目录中除了月末文件夹以外的其他文件夹,以保留10天的备份记录。脚本通过`date`、`cal`和`awk`等命令获取上个月最后一天和10天前的日期,然后进行条件判断并删除不再保留范围内的文件夹。此外,还提到了用`crontab`设置定时任务来定期执行此脚本。
摘要由CSDN通过智能技术生成

[root@linux26 test]# ls

2010-11-30  2010-12-01  2010-12-18  2010-12-20  2010-12-24  2010-12-31  44.sh  5.sh

2010-11-31  2010-12-17  2010-12-19  2010-12-23  2010-12-25  3.sh        4.sh   rm.sh

[root@linux26 test]# mkdir 2010-12-22

[root@linux26 test]# ls

2010-11-30  2010-12-01  2010-12-18  2010-12-20  2010-12-23  2010-12-25  3.sh   4.sh  rm.sh

2010-11-31  2010-12-17  2010-12-19  2010-12-22  2010-12-24  2010-12-31  44.sh  5.sh

[root@linux26 test]# date

Sat Jan  1 00:20:03 EST 2011

[root@linux26 test]# cat 44.sh

#!/bin/bash

month_last_day=`date -d '-1 month' +%Y-%m`"-"`cal|xargs echo|awk '{print $NF}'`

last_day=`date -d '-10 day' +%Y-%m-%d`

if [ "$last_day" != "$month_last_day" ];then

rm -rf $last_day

fi

[root@linux26 test]# sh -x 44.sh

++ date -d '-1 month' +%Y-%m

++ cal

++ xargs echo

++ awk '{print $NF}'

+ month_last_day=2010-12-31

++ date -d '-10 day' +%Y-%m-%d

+ last_day=2010-12-22

+ '[' 2010-12-22 '!=' 2010-12-31 ']'

+ rm -rf 2010-12-22

[root@linux26 test]# ls

2010-11-30  2010-12-01  2010-12-18  2010-12-20  2010-12-24  2010-12-31  44.sh  5.sh

2010-11-31  2010-12-17  2010-12-19  2010-12-23  2010-12-25  3.sh        4.sh   rm.sh

[root@linux26 test]# date -s 2011/01/10

Mon Jan 10 00:00:00 EST 2011

[root@linux26 test]# ls

2010-11-30  2010-12-01  2010-12-18  2010-12-20  2010-12-24  2010-12-31  44.sh  5.sh

2010-11-31  2010-12-17  2010-12-19  2010-12-23  2010-12-25  3.sh        4.sh   rm.sh

[root@linux26 test]# sh -x 44.sh

++ date -d '-1 month' +%Y-%m

++ cal

++ xargs echo

++ awk '{print $NF}'

+ month_last_day=2010-12-31

++ date -d '-10 day' +%Y-%m-%d

+ last_day=2010-12-31

+ '[' 2010-12-31 '!=' 2010-12-31 ']'

[root@linux26 test]# ls

2010-11-30  2010-12-01  2010-12-18  2010-12-20  2010-12-24  2010-12-31  44.sh  5.sh

2010-11-31  2010-12-17  2010-12-19  2010-12-23  2010-12-25  3.sh        4.sh   rm.sh

vi /etc/crontab

00 07 * * * root /root/clean.sh

service crond restart

即可。

说明:

目录下每天都会安装系统时间命名的目录备份文件,要求保留月末的那天的文件目录,删除文件原则是保留10天的目录。以防万一的时候可以用备份文件来恢复。所以保留10天,根据时间来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值