Linux下自動清理超過指定大小檔案
阿新 • • 發佈:2018-11-13
掃描某個目錄下的檔案,發現超過指定大小即清空
1)掃描目錄下的檔案
2)判斷檔案大小
3)清空大於指定檔案的內容
以byte為單位顯示檔案大小,然後和20M大小做對比. 20M換算成位元組為20971520這裡判斷是否大於20M,大於則使用echo 語句將對應檔案置空
20M=20 * 1024 * 1024=20971520 echo `expr 20 \* 1024 \* 1024`
方法1
可以使用dd命令建立一個20M的檔案,測試下:
dd if=/dev/zero of=/root/test/1.txt bs=1M count=20 [[email protected]test]# dd if=/dev/zero of=/root/test/1.txt bs=1M count=20 20+0 records in 20+0 records out 20971520 bytes (21 MB) copied, 0.0202923 s, 1.0 GB/s [[email protected] test]# ll -rw-r--r-- 1 root root 20971520 Nov 13 10:13 1.txt [[email protected] test]# du -sh 1.txt 20M 1.txt
處理指令碼:
#!/bin/bash for size in$(ls -l /root/test/* |awk '{print $5}') do for file in $(ls -l /root/test/* | grep $size |awk '{print $9}') do if [ ${size} -gt 62914560 ];then echo ${file} ${size} echo "" > ${file} fi done done
結合crontab進行定時執行
[[email protected] test]# chmod 755 scan_gt_20.sh
[[email protected] test]# /bin/bash -x scan_gt_20.sh
[[email protected] test]# crontab -e 0 2 * * 6 /bin/bash -x /root/test/scan_gt_20.sh > /dev/null 2>&1
方法2
"find -size" -size 選項用於查詢滿足指定的大小條件的檔案(注意不查詢目錄), +表示大於, -表示小於, 沒有+或-表示正好等於。
可以使用dd命令建立一個20M的檔案,測試下:
[[email protected] test]# dd if=/dev/zero of=/root/test/1.txt bs=1M count=21 21+0 records in 21+0 records out 22020096 bytes (22 MB) copied, 0.0259113 s, 850 MB/s [[email protected] test]# find ./ -type f -size +20M ./1.txt [[email protected] test]#
處理指令碼
[[email protected] test]# vi scan_gt_20.sh #!/bin/bash for i in $(find /root/test/* -size +20M); do echo " " > $i; done
[[email protected] test]# crontab -e 0 2 * * 6 /bin/bash -x /root/test/scan_gt_20.sh > /dev/null 2>&1