需求:查找某个目录下的所有超过一定大小的文件并清除
思路:查找此目录下的所有文件并判断其大小,超过一定大小则使用echo语句清空
方案:
使用du命令实现:
生成几个测试文件
[root@localhost cache]# dd if=/dev/zero of=testfile1 bs=1M count=50
50+0 records in
50+0 records out
52428800 bytes (52 MB) copied, 0.145185 s, 361 MB/s
[root@localhost cache]# dd if=/dev/zero of=testfile2 bs=1M count=60
60+0 records in
60+0 records out
62914560 bytes (63 MB) copied, 0.58209 s, 108 MB/s
[root@localhost cache]# dd if=/dev/zero of=testfile3 bs=1M count=80
80+0 records in
80+0 records out
83886080 bytes (84 MB) copied, 1.11964 s, 74.9 MB/s
[root@localhost cache]# echo "hello world" >testfile4
[root@localhost cache]# ll -h
total 191M
-rw-r--r-- 1 root root 50M Aug 11 20:44 testfile1
-rw-r--r-- 1 root root 60M Aug 11 20:44 testfile2
-rw-r--r-- 1 root root 80M Aug 11 20:44 testfile3
-rw-r--r-- 1 root root 12 Aug 11 20:45 testfile4
[root@localhost cache]# ll
total 194564
-rw-r--r-- 1 root root 52428800 Aug 11 20:44 testfile1 #这里文件大小单位为byte
-rw-r--r-- 1 root root 62914560 Aug 11 20:44 testfile2
-rw-r--r-- 1 root root 83886080 Aug 11 20:44 testfile3
-rw-r--r-- 1 root root 12 Aug 11 20:45 testfile4
[root@localhost cache]#
编写脚本,清理/cache目录下大小超过60M的文件
[root@localhost cache]# cat check.sh
#!/bin/bash
#sehn
for i in $(du -sh -b /cache/* | awk '{print $1}')
do
for f in $(du -sh -b /cache/* | grep ${i} | awk '{print $2}')
do
if [ ${i} -gt 62914560 ]; then
echo ${f} ${i}
echo "" > ${f}
fi
done
done
[root@localhost cache]#
执行,大小超过60M的文件被清空
[root@localhost cache]# sh check.sh
/cache/testfile3 83886080
[root@localhost cache]# du -sh -b *
221 check.sh
52428800 testfile1
62914560 testfile2
1 testfile3
12 testfile4
[root@localhost cache]#
脚本内查看文件大小命令也可使用 ll命令,实现如下:
将/cache目录下大小超过50M的文件清空
[root@localhost cache]# cat check.sh
#!/bin/bash
#sehn
for i in $(ls -l /cache/* | awk '{print $5}')
do
for f in $(ls -l /cache/* | grep ${i} | awk '{print $9}')
do
if [ ${i} -gt 52428800 ]; then
echo ${f} ${i}
echo "" > ${f}
fi
done
done
[root@localhost cache]# sh check.sh
/cache/testfile2 62914560
[root@localhost cache]# ll
total 51216
-rw-r--r-- 1 root root 213 Aug 11 21:05 check.sh
-rw-r--r-- 1 root root 52428800 Aug 11 20:59 testfile1
-rw-r--r-- 1 root root 1 Aug 11 21:05 testfile2
-rw-r--r-- 1 root root 1 Aug 11 20:59 testfile3
-rw-r--r-- 1 root root 12 Aug 11 20:45 testfile4
[root@localhost cache]#
使用find命令也可以,实现如下:
将/cache目录下大小超过40M的文件清空
[root@localhost cache]# cat check_find.sh
#!/bin/bash
for i in $(find /cache/ -size +40M);
do
echo " " > $i;
done
[root@localhost cache]# sh check_find.sh
[root@localhost cache]# ll
total 24
-rw-r--r-- 1 root root 75 Aug 11 21:08 check_find.sh
-rw-r--r-- 1 root root 213 Aug 11 21:05 check.sh
-rw-r--r-- 1 root root 2 Aug 11 21:09 testfile1
-rw-r--r-- 1 root root 1 Aug 11 21:05 testfile2
-rw-r--r-- 1 root root 1 Aug 11 20:59 testfile3
-rw-r--r-- 1 root root 12 Aug 11 20:45 testfile4
[root@localhost cache]#
结合crontab定时任务自动清理(建议将脚本放到其他目录)
[root@localhost cache]# crontab -l
0 2 * * 6 /bin/bash -x /cache/check.sh > /dev/null 2>&1