【问题标题】:Shell script to delete files when disk is full磁盘已满时删除文件的 Shell 脚本
【发布时间】:2021-04-28 15:55:43
【问题描述】:

如果缓存目录变得太大,我每天都会通过 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 ( current working directory = /home/user/lotsa_cache_files/)' 部分只是我内心的偏执狂的一种防御机制。在继续执行删除命令之前,我想确保我确实在“/home/user/lotsa_cache_files/”中,如果当前工作目录由于某种原因不存在,则可能具有破坏性。

删除文件

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

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

这是由于 linux 系统固有地无法在目录包含太多文件时“管理”一个目录,正如我过去所了解的那样。

【问题讨论】:

  • "如果目录包含太多文件,Linux 系统固有地无法 'rm' 一个目录" 这是否也意味着 "rm -rf"?

标签: linux bash shell


【解决方案1】:

只是另一个提议(代码中的 cmets):

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 调用脚本以执行计划清理

【讨论】:

  • 我建议使用-delete 标志而不是-exec rm -f {} \;。还可以考虑添加 -xdev 作为第一个标志以留在同一文件系统中。
【解决方案2】:

我会这样做:

# 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,因为它可能很危险。
【解决方案3】:

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

#!/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 它会 cd $DIR 所以它不会。
【解决方案4】:

为了检测文件系统的占用情况,我使用这个:

df -k $FILESYSTEM | tail -1 | awk '{print $5}'

这给了我文件系统的占用百分比,这样我就不需要计算它了:)

如果你使用bash,可以使用pushd/popd操作换目录,一定要进去。

pushd '/home/user/lotsa_cache_files/'
do the stuff
popd

【讨论】:

    【解决方案5】:

    这是我的工作:

    while read f; do rm -rf ${f}; done &lt; movies-to-delete.txt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 2018-12-31
      相关资源
      最近更新 更多