用于在磁盘已满时删除文件的Shell脚本

Roy*_*Roy 10 linux bash 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/
        }
    }
Run Code Online (Sandbox Code Playgroud)

获得驱动器空间

我打算从'/ dev/sda5'命令中获取驱动器空间.如果您的信息返回以下值:

Filesystem           1K-blocks      Used Available Use% Mounted on<br>
/dev/sda5            225981844 202987200  11330252  95% /
Run Code Online (Sandbox Code Playgroud)

因此,可能需要一点正则表达式才能使'11330252'超出返回值

有点偏执狂

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

删除文件

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

find . -name "*" -print | xargs rm
Run Code Online (Sandbox Code Playgroud)

这是因为Linux系统固有的无法"rm"目录,如果它包含太多文件,正如我过去所了解的那样.

hmo*_*liu 13

只是另一个提案(代码内的评论):

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 
Run Code Online (Sandbox Code Playgroud)

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

  • 我建议使用“-delete”标志而不是“-exec rm -f {} \;”。还可以考虑添加“-xdev”作为第一个标志以保留在同一文件系统中。 (2认同)

bmk*_*bmk 8

我会这样做:

# get the available space left on the device
size=$(df -k /dev/sda5 | tail -1 | awk '{print $4}')

# check if the available space is smaller than 5GB (5000000kB)
if (($size<5000000)); then
  # find all files under /home/user/lotsa_cache_files and delete them
  find /home/user/lotsa_cache_files -name "*" -delete
fi
Run Code Online (Sandbox Code Playgroud)