zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Android Studio打开非本机项目比较慢的问题。
    Servlet实现重定向的两种方式
    Servlet实现定时刷新到另外一个页面response.setHeader("refresh", "3;url=/...")
    Servlet实现自动刷新功能
    自己实现一个验证码功能
    使用Servlet实现图片下载
    数据库备份的几种方法
    servlet实现的三种方式对比(servlet 和GenericServlet和HttpServlet)
    java中this的用法如:this.name=name
    步骤一:下载jdk并安装和配置java环境变量
  • 原文地址:https://www.cnblogs.com/dengcongcong/p/9950929.html
Copyright © 2011-2022 走看看