微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux-Shell脚本在磁盘已满时删除文件

如果缓存目录太大,我每天都会通过CRON编写一个小的脚本来清除Linux上的空间.
由于我对bash脚本非常了解,因此我将需要您的linux专家的帮助.

这基本上是逻辑(伪代码)

    if ( Drive Space Left < 5GB )
    {
        change directory to '/home/user/lotsa_cache_files/'

        if ( current working directory = '/home/user/lotsa_cache_files/')
        {
            delete files in /home/user/lotsa_cache_files/
        }
    }

剩余驱动器空间

我计划从“ / dev / sda5”命令获取驱动器空间.
如果返回以下值给我作为您的信息:

Filesystem           1K-blocks      Used Available Use% Mounted on<br>
/dev/sda5            225981844 202987200  11330252  95% /

因此,可能需要一些正则表达式才能使’11330252’脱离返回值

有点偏执

“ if(当前工作目录= / home / user / lotsa_cache_files /)”部分只是我内心偏执的一种防御机制.我要确保在执行删除命令之前确实确实在’/ home / user / lotsa_cache_files /’中,如果由于某种原因当前的工作目录不存在,则可能具有破坏性.

删除文件

删除文件将通过以下命令完成,而不是通常的rm -f:

find . -name "*" -print | xargs rm

如前所述,这是由于linux系统固有的无法在包含太多文件的目录中“ rm”存储的.

解决方法:

只是另一个建议(代码中的注释):

FILESYstem=/dev/sda1 # or whatever filesystem to monitor
CAPACITY=95 # delete if FS is over 95% of usage 
CACHEDIR=/home/user/lotsa_cache_files/

# Proceed if filesystem capacity is over than the value of CAPACITY (using df POSIX Syntax)
# using [ instead of [[ for better error handling.
if [ $(df -P $FILESYstem | awk '{ gsub("%",""); capacity = $5 }; END { print capacity }') -gt $CAPACITY ]
then
    # lets do some secure removal (if $CACHEDIR is empty or is not a directory find will exit
    # with error which is quite safe for missruns.):
    find "$CACHEDIR" --maxdepth 1 --type f -exec rm -f {} \;
    # remove "maxdepth and type" if you want to do a recursive removal of files and dirs
    find "$CACHEDIR" -exec rm -f {} \;
fi 

从crontab调用脚本以执行计划的清理

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐