Linux:基于ncdu命令的存储容量自动扫描统计工具

一、背景

设备存储容量不够时,需要删除清理无用文件,若文件目录较多,逐个去统计每个文件目录的存储占用量,比较麻烦。ncdu命令有一个比较好的扫描和删除交互界面,基于ncdu命令写一个定时自动统计脚本,可以帮助我们管理设备的存储空间。

二、实现脚本

1.定时自动统计脚本

#!/bin/bash

set -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; do
        sleep 1
        CURRENT_TIME=$(date +%H:%M)
        if [ "$CURRENT_TIME" == "00:00" ]; then
            break
        fi
    done
    sleep 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; then
        echo "The tool \"ncdu\" is not installed. Please install it by running:"
        echo ""
        echo "    apt install ncdu"
        echo ""
        exit 1
    fi
}

# Function to load the latest disk usage stats.
load_stats() {
    if [ -f "$SCAN_FILE" ]; then
        echo "Loading disk usage statistics from $SCAN_FILE..."
        gzip -dc "$SCAN_FILE" | ncdu -f -
    else
        echo "Scan file $SCAN_FILE does not exist."
        echo "Please ensure that the scan file exists or run the scanning script first."
        exit 1
    fi
}

# Main script execution.
check_ncdu
load_stats

这个脚本需要放在上述设置的WORK_DIR:扫描结果文件的存储目录下,执行后,自动获取最新的扫描统计文件。通过方向键进入或返回文件夹,"d"删除文件/文件夹,"q"退出。
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值