一、背景
设备存储容量不够时,需要删除清理无用文件,若文件目录较多,逐个去统计每个文件目录的存储占用量,比较麻烦。ncdu命令有一个比较好的扫描和删除交互界面,基于ncdu命令写一个定时自动统计脚本,可以帮助我们管理设备的存储空间。
二、实现脚本
1.定时自动统计脚本
#!/bin/bashset -ex# This script runs indefinitely, performing a disk usage scan every day.
WORK_DIR="/share/temp_to_del" #扫描结果文件的存储目录
SCAN_DIR="/share/" #需要扫描的目录while true; do# Get the current date and time.TIMESTAMP=$(date +%Y-%m-%d_%H-%M-%S)YEAR_MONTH=$(date +%Y-%m)# Define the output directory and ensure it exists.OUTPUT_DIR="$WORK_DIR/${YEAR_MONTH}"mkdir -p "$OUTPUT_DIR"# Define the output file path.OUTPUT_FILE="${OUTPUT_DIR}/scan_file_${TIMESTAMP}.ncdu.gz"# Run the ncdu command and save the output.ncdu -1xo- $SCAN_DIR | gzip > "$OUTPUT_FILE"# Update the latest symbolic link.ln -sf "${OUTPUT_FILE#$WORK_DIR/}" "$WORK_DIR/latest.ncdu.gz"# Sleep until the next day.while true; dosleep 1CURRENT_TIME=$(date +%H:%M)if [ "$CURRENT_TIME" == "00:00" ]; thenbreakfidonesleep 259200 #扫描统计的间隔时间,单位秒
done
需要设置项:
1.WORK_DIR:扫描结果文件的存储目录
2.SCAN_DIR:需要扫描的目录
3.间隔时间
这个脚本会将扫描结果保存为后缀".ncdu,gz"的文件,存储到对应月份的文件夹中
2.可视化及删除脚本
#!/bin/bash# This script checks if ncdu is installed and loads the latest disk usage stats.# Define the path to the latest scan file.
SCRIPT_DIR=$(dirname `realpath $0`)
SCAN_FILE="$SCRIPT_DIR/latest.ncdu.gz"# Function to check if ncdu is installed.
check_ncdu() {if ! command -v ncdu &> /dev/null; thenecho "The tool \"ncdu\" is not installed. Please install it by running:"echo ""echo " apt install ncdu"echo ""exit 1fi
}# Function to load the latest disk usage stats.
load_stats() {if [ -f "$SCAN_FILE" ]; thenecho "Loading disk usage statistics from $SCAN_FILE..."gzip -dc "$SCAN_FILE" | ncdu -f -elseecho "Scan file $SCAN_FILE does not exist."echo "Please ensure that the scan file exists or run the scanning script first."exit 1fi
}# Main script execution.
check_ncdu
load_stats
这个脚本需要放在上述设置的WORK_DIR:扫描结果文件的存储目录下,执行后,自动获取最新的扫描统计文件。通过方向键进入或返回文件夹,"d"删除文件/文件夹,"q"退出。