当磁盘已满时,使用Shell脚本删除文件

14

我正在编写一个小脚本,如果缓存目录过大,每天通过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”命令删除该目录,这是我过去所学到的。


3
Linux系统固有的缺陷之一是如果一个目录中包含太多文件,它无法使用"rm"命令删除。这是否也适用于"rm -rf"命令? - rzetterberg
5个回答

21

又一个建议(代码内有注释):

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调用脚本进行定时清理


2
我建议使用 -delete 标志而不是 -exec rm -f {} \;。另外,考虑将 -xdev 添加为第一个标志以保留在同一文件系统中。 - Emil Vikström
如果您想保留最新的文件,我建议使用以下命令:find "$CACHEDIR" -type f -mmin +720 -delete,该命令将只删除12小时前的文件(*60分钟=720)。 - Philippe

10

我会这样做:

# 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

这就是我要推荐的:在“find”命令中硬编码目录,不要使用xargs,因为它可能很危险。 - David W.

4
以下是我用来删除目录中旧文件以释放空间的脚本...

以下是我用来删除目录中旧文件以释放空间的脚本...

#!/bin/bash
#
#  prune_dir - prune directory by deleting files if we are low on space
#
DIR=$1
CAPACITY_LIMIT=$2

if [ "$DIR" == "" ]
then
    echo "ERROR: directory not specified"
    exit 1
fi

if ! cd $DIR
then
    echo "ERROR: unable to chdir to directory '$DIR'"
    exit 2
fi

if [ "$CAPACITY_LIMIT" == "" ]
then
    CAPACITY_LIMIT=95   # default limit
fi

CAPACITY=$(df -k . | awk '{gsub("%",""); capacity=$5}; END {print capacity}')

if [ $CAPACITY -gt $CAPACITY_LIMIT ]
then
    #
    # Get list of files, oldest first.
    # Delete the oldest files until
    # we are below the limit. Just
    # delete regular files, ignore directories.
    #
    ls -rt | while read FILE
    do
        if [ -f $FILE ]
        then
            if rm -f $FILE
            then
                echo "Deleted $FILE"

                CAPACITY=$(df -k . | awk '{gsub("%",""); capacity=$5}; END {print capacity}')

                if [ $CAPACITY -le $CAPACITY_LIMIT ]
                then
                    # we're below the limit, so stop deleting
                    exit
                fi
            fi
        fi
    done
fi

请再次检查代码!看起来它将删除当前文件夹中的文件。 - Max
@Max它执行的是cd $DIR,所以不会。 - dgpro

3
为了检测文件系统的使用情况,我使用以下代码:
df -k $FILESYSTEM | tail -1 | awk '{print $5}'

这样我就可以得到文件系统的使用百分比,无需计算 :) 如果您使用bash,可以使用pushd/popd操作更改目录并确保在其中。
pushd '/home/user/lotsa_cache_files/'
do the stuff
popd

-2
这是我的做法: ``` while read f; do rm -rf ${f}; done < movies-to-delete.txt ```

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接