目录容量保持自动删除旧文件
#!/bin/bash
clean_old_files() {
local target_dir=$1
local total_capacity_gb=$2
local threshold=$3
# 获取文件夹的实际使用空间(单位为KB)
local used_kb=$(du -s "$target_dir" | awk '{print $1}')
# 将总容量转换为KB
local total_kb=$((total_capacity_gb * 1024 * 1024))
# 计算使用空间百分比
local used_percent=$((used_kb * 100 / total_kb))
echo "当前文件夹使用空间:$used_percent%"
if [ "$used_percent" -ge "$threshold" ]; then
echo "磁盘使用超过 $threshold%,开始清理文件..."
# 需要清理的目标大小(占总容量的 10%)
local target_clean_kb=$((total_kb / 10))
local cleaned_kb=0
# 查找所有文件,按修改时间排序
find "$target_dir" -type f -exec stat --format='%Y %s %n' {} \; | sort -n | while read -r line; do
# 提取文件大小和路径
file_size=$(echo "$line" | awk '{print $2}')
file_size=$((file_size / 1024))
file_path=$(echo "$line" | cut -d' ' -f3-)
# 删除文件
echo "删除文件: $file_path (大小: $file_size KB)"
rm -f "$file_path"
# 累加已清理大小
cleaned_kb=$((cleaned_kb + file_size))
# 判断是否达到目标清理大小
if [ "$cleaned_kb" -ge "$target_clean_kb" ]; then
echo "已清理 $cleaned_kb KB,达到目标大小 $target_clean_kb KB。"
break
fi
done
else
echo "磁盘使用未达到 $threshold%,无需清理。"
fi
}
# 无限循环每小时执行一次
while true; do
clean_old_files $1 $2 $3
sleep 3600 # 暂停一小时
done
clean.sh /yourPath 10 90
脚本名 目录路径 预设大小GB 到达删除容量的百分比