根据阈值删除文件的脚本

根据阈值删除文件的脚本

我的 Linux 服务器中有一些旧文件,我需要根据阈值删除那些超过 5 天的文件。

log_space_checker() {
        Use=$(df -kh /logs | awk 'END{gsub("%",""); print $4}');
        DATAUSE=$(df -kh /logs | awk 'END{gsub("%",""); print $4}');
}

remove_files(){
        RemoveFiles="/logs/abc/abc.log.*"
        find "$RemoveFiles" -mtime +1 -type f -delete
        }

disk_space_monitor() {
        log_space_checker;

        if [[ $DATAUSE -gt $TH ]] ; then
                remove_files;
        fi

}

TH=7

disk_space_monitor

脚本正确吗?

答案1

我,我会去做这样的事情

#!/bin/bash
#

########################################################################
#
log_space_checker() {
    local target="$1"                 # Log file template
    local directory="${target%/*}"    # Directory holding log files
    df -k "$directory" | awk 'NR>1 {print gensub("^.* ([1-9][0-9]*)%.*", "\\1", 1)}'
}

########################################################################
#
remove_files(){
    local logfiles="$1"               # Log file template
    find $logfiles -mtime +1 -type f -print ## -delete
}

########################################################################
#
disk_space_monitor() {
    local threshold="$1"              # Threshold%
    local target="$2"                 # Log files to delete 
    local pct_used=$(log_space_checker "$2");

    if [[ $pct_used -gt $threshold ]]
    then
        remove_files "$2"
    fi
}

########################################################################
# Go
#
threshold=7                           # % usage above which we will delete
logfiles='/logs/abc/abc.log.*'        # ...log files matching this pattern

disk_space_monitor "$threshold" "$logfiles"

相关内容