• Linux下自动清理超过指定大小文件


    作者:邓聪聪

      扫描某个目录下的文件,发现超过指定大小即清空

    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
    [root@admin 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
    [root@admin test]# ll
    -rw-r--r--  1 root root 20971520 Nov 13 10:13 1.txt
    [root@admin 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进行定时执行

    [root@admin test]# chmod 755 scan_gt_20.sh
    [root@admin test]# /bin/bash -x scan_gt_20.sh
    [root@admin 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的文件,测试下:

    [root@admin 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
    [root@admin test]# find ./ -type f -size +20M                        
    ./1.txt
    [root@admin test]#

     处理脚本

    [root@admin test]# vi scan_gt_20.sh
    #!/bin/bash
    for i in $(find /root/test/* -size +20M);
    do
       echo " " > $i;
    done
    [root@admin test]# crontab -e
    0 2 * * 6 /bin/bash -x /root/test/scan_gt_20.sh > /dev/null 2>&1
  • 相关阅读:
    课程作业四 生成随机数并求和,大数运算
    课程作业三 string,char操作
    课程作业二 类内静态内容(代码块,静态变量),构造函数,非静态代码块执行顺序
    十一作业 java数值范围方面训练
    课程作业一 将字符串型数组里的数字相加
    NABCD需求分析
    人月神话阅读笔记01
    软件工程第五周总结
    清明第三天
    清明第二天安排
  • 原文地址:https://www.cnblogs.com/dengcongcong/p/9950929.html
Copyright © 2020-2023  润新知