Linux 磁盘已满时删除文件的Shell脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5908919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:58:16  来源:igfitidea点击:

Shell script to delete files when disk is full

linuxbashshell

提问by Roy

I am writing a small little script to clear space on my linux everyday via CRON if the cache directory grows too large. Since I am really green at bash scripting, I will need a little bit of help from you linux gurus out there.

如果缓存目录变得太大,我正在编写一个小的脚本来每天通过 CRON 清除我的 linux 上的空间。由于我对 bash 脚本编写非常熟悉,因此我需要一些 linux 专家的帮助。

Here is basically the logic (pseudo-code)

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

    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/
        }
    }

Getting drive space left

获得剩余驱动器空间

I plan to get the drive space left from the '/dev/sda5' command. If returns the following value to me for your info :

我计划从“/dev/sda5”命令中获得剩余的驱动器空间。如果将以下值返回给我以获取您的信息:

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

So a little regex might be necessary to get the '11330252' out of the returned value

因此,可能需要一些正则表达式才能从返回值中获取“11330252”

A little paranoia

有点偏执

The 'if ( current working directory = /home/user/lotsa_cache_files/)' part is just a defensive mechanism for the paranoia within me. I wanna make sure that I am indeed in '/home/user/lotsa_cache_files/' before I proceed with the delete command which is potentially destructive if the current working directory is not present for some reason.

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

Deleting files

删除文件

The deletion of files will be done with the command below instead of the usual rm -f:

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

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

This is due to the inherent inability of linux systems to 'rm' a directory if it contains too many files, as I have learnt in the past.

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

采纳答案by hmontoliu

Just another proposal (comments within code):

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

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 =  }; 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 

Call the script from crontab to do scheduled cleanings

从 crontab 调用脚本来执行预定的清理

回答by Cédric Julien

To detect the occupation of a filesystem, I use this :

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

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

which give me the occupation percentage of the filesystem, this way, I do not need to compute it :)

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

If you use bash, you can use the pushd/popd operation to change directory and be sure to be in.

如果你使用bash,你可以使用pushd/popd操作来改变目录,并且一定要在。

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

回答by bmk

I would do it this way:

我会这样做:

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

# 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

回答by lfjeff

Here's the script I use to delete old files in a directory to free up space...

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

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

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=}; 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=}; END {print capacity}')

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