Bash脚本,如果空闲大小超过阈值,则从目录中递归删除最旧的文件

问题描述 投票:0回答:2

我正在寻找一个脚本,如果分区上的空闲空间小于5%,则从目录中删除文件(最早的)。

我找到了以下脚本:

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 

据我所知,如果$ FILESYSTEM上使用的空间超过$ CAPACITY%,则从CACHEDIR中删除文件。

但是,我不确定这是否有效,但我确信它不会删除最早的第一个。

我希望它删除最小数量的文件(从最旧到最新)以释放空间。

linux bash shell ubuntu
2个回答
2
投票

如果/ dev / sda1超过95%已满,您的脚本将删除$CACHEDIR中的每个文件。做这样的事情:

#!/bin/bash

DIRECTORY="/path/to/your/directory"
CAPACITY=95
while [[ $(df $DIRECTORY | awk 'NR==2 && gsub("%","") {print$5}') -ge $CAPACITY ]];do
        rm -rf $(find $DIRECTORY -mindepth 1 -printf '%T+ %p\n' | sort | awk 'NR==1 {print$2}')
done

您可以在crontab上运行此脚本,或者执行while循环并使用systemd对其进行守护,以便它在后台继续运行并在每次分区达到95%时删除文件。

解释:

df $DIRECTORY跟踪目录分区并打印它的信息。 awk 'NR==2 && gsub("%","") {print$5}'打印第二行(相关的一行,首先是标题),删除百分号并打印第5列(“使用%”列)。 rm -rf删除以下命令的结果。 find $DIRECTORY -mindepth 1 -printf '%T+ %p\n' | sort | awk 'NR==1 {print$2}'找到$DIRECTORY并打印文件的修改日期,然后sort它并打印第一行(最旧的一个)的第二个字段(文件名)。


0
投票

如何使用ls来删除文件?

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
    # Remove the oldest file in CACHEDIR:
    # rm $CACHEDIR/$( ls -t $CACHEDIR | tail -1 )
    rm $CACHEDIR/$( ls -tp $CACHEDIR | sed '/\/$/d' | tail -1 )
fi 
© www.soinside.com 2019 - 2024. All rights reserved.