如果缓存目录太大,我每天都会通过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
/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调用脚本以执行计划的清理
标签:bash,linux,shell
来源: https://codeday.me/bug/20191010/1887166.html