问题描述
很多公司需要当天定时多次备份数据库,创建当天日期的目录及目录内存放当天备份数据,用网上的脚本出现把整个数据库备份给删除了,下面给出了错误经过和解决的方法,给同行们参考,注意下操作任何文件请先!!!!备份数据 !!!再测试脚本!!!!
脚本需求
删除几天前数据库备份的目录及文件。
1.搭建模拟环境
因为之前的环境已经搞定了,这个模拟下,让大家了解下,不需要的直接看第二部分
[[email protected] ~]#mkdir /mysql/{20160401,20160402,20160403.20160404} #创建模拟数据库备份夹
[[email protected] ~]#touch /mysql/2016040{1,2,3,4}/1111 #创建模拟数据库备份文件
[[email protected] ~]# tree /mysq #查看目录结构有没有少文件
/mysql
├── 20160401
│?? └── 1111
├── 20160402
│?? └── 1111
├── 20160403
│?? └── 1111
└── 20160404
└── 1111
[[email protected] ~]# touch -d "04/01/2016" /mysql/20160401 #修改文件目录时间戳
[[email protected] ~]# touch -d "04/02/2016" /mysql/20160402
[[email protected] ~]# touch -d "04/03/2016" /mysql/20160403
[[email protected] ~]# touch -d "04/01/2016" /mysql/20160401/1111 #修改文件子目录时间戳
[[email protected] ~]# touch -d "04/02/2016" /mysql/20160402/1111 #重要的是"04/02/2016",一开始我写成"02/04/2016",结果完全不一样
[[email protected] ~]# touch -d "04/03/2016" /mysql/20160403/1111 #最后查找的结果完全不一样,给自己挖坑
[[email protected] ~]# stat /mysql/20160402/1111 #随便查看修改后的时间戳
File: ‘/mysql/20160402/1111’
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: 801h/2049d Inode: 23566090 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Context: unconfined_u:object_r:default_t:s0
Access: 2016-04-02 00:00:00.000000000 +0800 #已经变了
Modify: 2016-04-02 00:00:00.000000000 +0800 #已经变了
Change: 2016-04-04 02:09:03.395105983 +0800
Birth: -
2.开始演示错误命令
网络上查到都是这样的
[[email protected] ~]#find /mysql/ -type d -o -type f -ctime +1 -exec rm -rf {} \;
#后面执行的语句暂时去掉“-exec rm -rf {} \;”先看看我们搜索到的结果
#因为我是改的时间戳所以-ctime,我改成-mtime测试,效果一样
#后果是什么呢呵呵,全删,因为找到了所有目录,所有连主/mysql都删掉了
#很多书上和网上都是这样的命令,坑哭了多少同胞
[[email protected] ~]# find /mysql/ -type d -o -type f -mtime +1
/mysql/
/mysql/20160401
/mysql/20160401/1111
/mysql/20160402
/mysql/20160402/1111
/mysql/20160404
/mysql/20160403
[[email protected] ~]# find /mysql/ -type d -o -type f -mtime +2
/mysql/
/mysql/20160401
/mysql/20160401/1111
/mysql/20160402
/mysql/20160404
/mysql/20160403
3.正确命令演示
#既然要删除目录和文件为什么还要加上“-type d -o -type f”呢
#不经过测试的脚本会死的很惨
[[email protected] ~]# find /mysql/ -mtime +1
/mysql/20160401
/mysql/20160401/1111
/mysql/20160402
/mysql/20160402/1111
[[email protected] ~]# find /mysql/ -mtime +2
/mysql/20160401
/mysql/20160401/1111
#命令完全版测试结果
[[email protected] ~]# find /mysql/ -mtime +2 -exec rm -rf {} \;
find: ‘/mysql/20160401’: No such file or directory
[[email protected] ~]# find /mysql/ -mtime +2
[[email protected] ~]# ls /mysql/2016040* #查找后确实连目录都删掉了,其他没有文件没有影响
/mysql/20160402:
1111
/mysql/20160403:
1111
/mysql/20160404:
1111