【问题标题】:Is there a way to automatically delete files in the tmp folder?有没有办法自动删除tmp文件夹中的文件?
【发布时间】:2017-09-02 20:44:26
【问题描述】:

有没有办法在 Ubuntu 的容量超过 80% 或一个月后自动删除 tmp 文件夹中带有 thumb 扩展名的文件?

我应该使用 crontab 吗?还是应该同时写crontab和shellscript?

【问题讨论】:

    标签: shell ubuntu cron


    【解决方案1】:

    在我看来,您可以使用基于年龄删除文件的标准方法,如果文件系统太满,稍作修改以降低阈值。

    删除/tmp中超过一定年龄(大约一个月)的所有*.thumb文件的常规方法是使用如下命令:

    find /tmp -type f -name '*.thumb' -mtime +30 -delete
    

    所以,你需要做的就是在某些情况下修改mtime测试来降低阈值。要根据文件系统的完整程度来执行此操作,可以使用以下方法:

    #!/usr/bin/env bash
    
    # Default to about a month.
    
    thresh=30
    
    # Get percentage used of /tmp, needs to match output of df, such as:
    #  Filesystem     1K-blocks      Used Available Use% Mounted on
    #  tmp              1000000    280000    720000  28% /tmp
    
    tmppct=$(df | awk '$6=="/tmp" { gsub("%", "", $5); print $5 }')
    
    # Reduce threshold if tmp more than 80% full.
    
    [[ ${tmppct} -gt 80 ]] && thresh=1
    
    # Go and clean up, based on threshold.
    
    find /tmp -type f -name '*.thumb' -mtime +${thresh} -delete
    

    该脚本唯一可能棘手的一点是将df 的输出(基于指定的格式)通过:

    awk '$6=="/tmp" { gsub("%", "", $5); print $5 }'
    

    这只是:

    • 查找第六个字段为/tmp 的行;
    • 从第五个字段中删除尾随%;和
    • 最终输出(修改后的)第五个字段以捕获已满百分比。

    然后只需创建一个crontab 条目,它将定期运行该脚本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 2021-02-08
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      相关资源
      最近更新 更多