df 命令详解#
df(Disk Free)是 Linux 系统中用于显示文件系统磁盘空间使用情况的命令。它可以显示每个挂载点的总容量、已用空间、可用空间和使用百分比,是系统管理员进行磁盘空间管理的重要工具。
入门#
基本用法#
# 显示磁盘空间使用情况
df
# 以人类可读格式显示
df -h
# 显示特定文件系统
df /home
# 显示所有文件系统
df -a常用选项#
| 选项 | 说明 |
|---|---|
-h | 以人类可读格式显示(KB、MB、GB) |
-a | 显示所有文件系统 |
-T | 显示文件系统类型 |
-i | 显示 inode 使用情况 |
-x | 排除特定文件系统类型 |
-t | 显示特定文件系统类型 |
基本示例#
# 显示磁盘空间使用情况
df
# 输出示例:
# Filesystem 1K-blocks Used Available Use% Mounted on
# /dev/sda1 10240000 5123456 5116544 51% /
# /dev/sda2 20480000 10234567 10245433 51% /home
# /dev/sda3 5120000 2567890 2552110 51% /var
# 以人类可读格式显示
df -h
# 输出示例:
# Filesystem Size Used Avail Use% Mounted on
# /dev/sda1 10G 4.9G 4.9G 51% /
# /dev/sda2 20G 9.8G 9.8G 51% /home
# /dev/sda3 5.0G 2.5G 2.5G 51% /var中级#
文件系统筛选#
# 显示特定文件系统类型
df -t ext4
# 排除特定文件系统类型
df -x tmpfs
# 显示多个文件系统类型
df -t ext4 -t xfs
# 显示特定挂载点
df /home
# 显示多个挂载点
df /home /var /tmpinode 使用情况#
# 显示 inode 使用情况
df -i
# 以人类可读格式显示 inode
df -ih
# 显示特定文件系统的 inode
df -i /home
# 输出示例:
# Filesystem Inodes IUsed IFree IUse% Mounted on
# /dev/sda1 655360 123456 531904 19% /
# /dev/sda2 1310720 567890 742830 44% /home
# /dev/sda3 327680 234567 93113 72% /var输出格式控制#
# 显示文件系统类型
df -T
# 显示特定字段
df -h --output=source,fstype,size,used,avail,pcent,target
# 显示完整路径
df -h --output=all
# 显示 POSIX 格式
df -P
# 显示总计
df -h --total高级#
高级筛选和显示#
# 显示所有文件系统(包括虚拟文件系统)
df -a
# 显示本地文件系统
df -l
# 显示特定块大小
df --block-size=1M
# 显示同步状态
df --sync
# 显示无缓存状态
df --no-sync
# 组合使用
df -hT --total磁盘空间监控#
#!/bin/bash
# 磁盘空间监控脚本
ALERT_THRESHOLD=80
ALERT_EMAIL="admin@example.com"
# 检查磁盘空间
check_disk_space() {
local mount_point=$1
local threshold=$2
local usage=$(df -h $mount_point | awk 'NR==2 {print $5}' | cut -d'%' -f1)
echo "Disk usage for $mount_point: ${usage}%"
if [ $usage -gt $threshold ]; then
echo "ALERT: Disk space low on $mount_point: ${usage}%"
echo "Disk space low on $mount_point: ${usage}%" | mail -s "Disk Alert" $ALERT_EMAIL
return 1
else
return 0
fi
}
# 检查所有挂载点
check_all_mounts() {
df -h | awk 'NR>1 {print $6}' | while read mount_point; do
check_disk_space $mount_point $ALERT_THRESHOLD
done
}
# 主函数
main() {
case "$1" in
check)
check_disk_space "$2" "$3"
;;
all)
check_all_mounts
;;
*)
echo "Usage: $0 {check|all}"
exit 1
;;
esac
}
main "$@"磁盘空间分析#
#!/bin/bash
# 磁盘空间分析脚本
# 生成磁盘空间报告
generate_disk_report() {
local report_file="disk_report_$(date +%Y%m%d_%H%M%S).txt"
echo "Disk Space Report - $(date)" > $report_file
echo "=====================" >> $report_file
echo "" >> $report_file
# 总体磁盘使用情况
echo "=== Overall Disk Usage ===" >> $report_file
df -h >> $report_file
echo "" >> $report_file
# 文件系统类型
echo "=== Filesystem Types ===" >> $report_file
df -hT >> $report_file
echo "" >> $report_file
# inode 使用情况
echo "=== Inode Usage ===" >> $report_file
df -ih >> $report_file
echo "" >> $report_file
# 高使用率文件系统
echo "=== High Usage Filesystems (>80%) ===" >> $report_file
df -h | awk 'NR>1 && $5+0 > 80 {print $0}' >> $report_file
echo "Report saved to: $report_file"
}
# 查找大文件
find_large_files() {
local directory=$1
local size=${2:-100M}
echo "Finding files larger than $size in $directory..."
find $directory -type f -size +$size -exec ls -lh {} \; | awk '{print $9, $5}'
}
# 分析磁盘增长
analyze_disk_growth() {
local mount_point=$1
local history_file="disk_history_${mount_point//\//_}.txt"
local current_usage=$(df -h $mount_point | awk 'NR==2 {print $3}')
local current_avail=$(df -h $mount_point | awk 'NR==2 {print $4}')
local current_percent=$(df -h $mount_point | awk 'NR==2 {print $5}')
echo "$(date '+%Y-%m-%d %H:%M:%S'),$current_usage,$current_avail,$current_percent" >> $history_file
echo "Disk usage recorded for $mount_point"
# 显示历史数据
if [ -f "$history_file" ]; then
echo ""
echo "History:"
tail -10 $history_file
fi
}
# 主函数
main() {
case "$1" in
report)
generate_disk_report
;;
large)
find_large_files "$2" "$3"
;;
growth)
analyze_disk_growth "$2"
;;
*)
echo "Usage: $0 {report|large|growth}"
exit 1
;;
esac
}
main "$@"大师#
企业级磁盘监控系统#
#!/bin/bash
# 企业级磁盘监控系统
CONFIG_FILE="/etc/disk_monitor/config.conf"
LOG_DIR="/var/log/disk_monitor"
METRICS_DB="/var/lib/disk_monitor/metrics.db"
mkdir -p $LOG_DIR $(dirname $METRICS_DB)
# 加载配置
source $CONFIG_FILE
# 收集磁盘指标
collect_disk_metrics() {
local timestamp=$(date +%s)
df -h | awk 'NR>1 {print $6, $2, $3, $4, $5}' | while read mount_point size used avail percent; do
local usage_percent=$(echo $percent | cut -d'%' -f1)
echo "$timestamp,$mount_point,$size,$used,$avail,$usage_percent" >> $METRICS_DB
# 检查告警阈值
if [ $usage_percent -gt $ALERT_THRESHOLD ]; then
log_message "ALERT: $mount_point usage: ${usage_percent}%"
send_alert "Disk space low on $mount_point: ${usage_percent}%"
fi
done
}
# 收集 inode 指标
collect_inode_metrics() {
local timestamp=$(date +%s)
df -i | awk 'NR>1 {print $6, $2, $3, $4, $5}' | while read mount_point total used free percent; do
local usage_percent=$(echo $percent | cut -d'%' -f1)
echo "$timestamp,$mount_point,inodes,$total,$used,$free,$usage_percent" >> $METRICS_DB
# 检查告警阈值
if [ $usage_percent -gt $INODE_ALERT_THRESHOLD ]; then
log_message "ALERT: $mount_point inode usage: ${usage_percent}%"
send_alert "Inode space low on $mount_point: ${usage_percent}%"
fi
done
}
# 分析磁盘趋势
analyze_disk_trend() {
local mount_point=$1
local duration=$2
local end_time=$(date +%s)
local start_time=$((end_time - duration))
echo "=== Disk Trend Analysis for $mount_point ==="
echo "Duration: $duration seconds"
echo ""
grep ",$mount_point," $METRICS_DB | awk -F, -v start=$start_time -v end=$end_time '$1 >= start && $1 <= end' | while read line; do
local timestamp=$(echo $line | cut -d, -f1)
local used=$(echo $line | cut -d, -f4)
local percent=$(echo $line | cut -d, -f6)
local formatted_time=$(date -d @$timestamp '+%Y-%m-%d %H:%M:%S')
echo "$formatted_time - Used: $used (${percent}%)"
done
}
# 生成监控报告
generate_monitor_report() {
local report_file="$LOG_DIR/monitor_report_$(date +%Y%m%d).txt"
echo "Disk Monitor Report - $(date +%Y-%m-%d)" > $report_file
echo "=====================" >> $report_file
echo "" >> $report_file
# 当前磁盘使用情况
echo "=== Current Disk Usage ===" >> $report_file
df -h >> $report_file
echo "" >> $report_file
# inode 使用情况
echo "=== Inode Usage ===" >> $report_file
df -ih >> $report_file
echo "" >> $report_file
# 高使用率文件系统
echo "=== High Usage Filesystems ===" >> $report_file
df -h | awk 'NR>1 && $5+0 > 80 {print $0}' >> $report_file
echo "" >> $report_file
# 趋势分析
echo "=== Disk Trends (last 24 hours) ===" >> $report_file
for mount_point in "${MONITORED_MOUNTS[@]}"; do
analyze_disk_trend $mount_point 86400 >> $report_file
echo "" >> $report_file
done
log_message "Monitor report generated: $report_file"
}
# 记录日志
log_message() {
local message=$1
local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
echo "[$timestamp] $message" >> $LOG_DIR/monitor.log
}
# 发送告警
send_alert() {
local message=$1
if [ "$ENABLE_EMAIL_ALERTS" = "true" ]; then
echo "$message" | mail -s "Disk Monitor Alert" $ALERT_EMAIL
fi
if [ "$ENABLE_SLACK_ALERTS" = "true" ]; then
curl -X POST -H 'Content-type: application/json' --data "{\"text\":\"$message\"}" $SLACK_WEBHOOK
fi
}
# 主监控循环
main_monitor() {
log_message "Disk Monitor started"
while true; do
collect_disk_metrics
collect_inode_metrics
# 每天生成一次报告
if [ $(date +%H) -eq 0 ] && [ $(date +%M) -eq 0 ]; then
generate_monitor_report
fi
sleep $COLLECT_INTERVAL
done
}
# 主函数
main() {
case "$1" in
monitor)
main_monitor
;;
analyze)
analyze_disk_trend "$2" "$3"
;;
report)
generate_monitor_report
;;
*)
echo "Usage: $0 {monitor|analyze|report}"
exit 1
;;
esac
}
main "$@"智能磁盘清理系统#
#!/bin/bash
# 智能磁盘清理系统
CONFIG_FILE="/etc/disk_cleaner/config.conf"
LOG_FILE="/var/log/disk_cleaner/cleaner.log"
mkdir -p $(dirname $LOG_FILE)
# 加载配置
source $CONFIG_FILE
# 清理临时文件
clean_temp_files() {
local temp_dirs=("/tmp" "/var/tmp" "/var/cache")
echo "Cleaning temporary files..."
for dir in "${temp_dirs[@]}"; do
if [ -d "$dir" ]; then
local size_before=$(du -sh $dir 2>/dev/null | awk '{print $1}')
find $dir -type f -mtime +${TEMP_FILE_AGE:-7} -delete 2>/dev/null
local size_after=$(du -sh $dir 2>/dev/null | awk '{print $1}')
echo " $dir: $size_before -> $size_after"
log_message "Cleaned $dir: $size_before -> $size_after"
fi
done
}
# 清理日志文件
clean_log_files() {
local log_dirs=("/var/log" "/var/log/journal")
echo "Cleaning log files..."
for dir in "${log_dirs[@]}"; do
if [ -d "$dir" ]; then
local size_before=$(du -sh $dir 2>/dev/null | awk '{print $1}')
find $dir -type f -name "*.log" -mtime +${LOG_FILE_AGE:-30} -delete 2>/dev/null
find $dir -type f -name "*.gz" -mtime +${LOG_FILE_AGE:-30} -delete 2>/dev/null
local size_after=$(du -sh $dir 2>/dev/null | awk '{print $1}')
echo " $dir: $size_before -> $size_after"
log_message "Cleaned $dir: $size_before -> $size_after"
fi
done
}
# 清理包管理器缓存
clean_package_cache() {
echo "Cleaning package manager cache..."
if command -v apt-get &> /dev/null; then
local size_before=$(du -sh /var/cache/apt 2>/dev/null | awk '{print $1}')
apt-get clean
apt-get autoremove -y
local size_after=$(du -sh /var/cache/apt 2>/dev/null | awk '{print $1}')
echo " APT cache: $size_before -> $size_after"
log_message "Cleaned APT cache: $size_before -> $size_after"
fi
if command -v yum &> /dev/null; then
local size_before=$(du -sh /var/cache/yum 2>/dev/null | awk '{print $1}')
yum clean all
local size_after=$(du -sh /var/cache/yum 2>/dev/null | awk '{print $1}')
echo " YUM cache: $size_before -> $size_after"
log_message "Cleaned YUM cache: $size_before -> $size_after"
fi
}
# 清理旧备份
clean_old_backups() {
local backup_dir=$1
local retention_days=${2:-30}
if [ -d "$backup_dir" ]; then
echo "Cleaning old backups in $backup_dir..."
local size_before=$(du -sh $backup_dir 2>/dev/null | awk '{print $1}')
find $backup_dir -type f -mtime +$retention_days -delete 2>/dev/null
local size_after=$(du -sh $backup_dir 2>/dev/null | awk '{print $1}')
echo " $backup_dir: $size_before -> $size_after"
log_message "Cleaned $backup_dir: $size_before -> $size_after"
fi
}
# 清理用户缓存
clean_user_cache() {
local users=$(ls /home)
echo "Cleaning user caches..."
for user in $users; do
local user_cache="/home/$user/.cache"
if [ -d "$user_cache" ]; then
local size_before=$(du -sh $user_cache 2>/dev/null | awk '{print $1}')
find $user_cache -type f -mtime +${USER_CACHE_AGE:-7} -delete 2>/dev/null
local size_after=$(du -sh $user_cache 2>/dev/null | awk '{print $1}')
echo " $user cache: $size_before -> $size_after"
log_message "Cleaned $user cache: $size_before -> $size_after"
fi
done
}
# 智能清理
smart_clean() {
local mount_point=$1
local threshold=${2:-80}
local usage=$(df -h $mount_point | awk 'NR==2 {print $5}' | cut -d'%' -f1)
if [ $usage -gt $threshold ]; then
echo "Disk usage high (${usage}%), starting smart clean..."
log_message "Smart clean triggered for $mount_point: ${usage}%"
clean_temp_files
clean_log_files
clean_package_cache
clean_user_cache
local new_usage=$(df -h $mount_point | awk 'NR==2 {print $5}' | cut -d'%' -f1)
echo "Disk usage after clean: ${new_usage}%"
log_message "Disk usage after clean: ${new_usage}%"
else
echo "Disk usage normal (${usage}%), no clean needed"
fi
}
# 记录日志
log_message() {
local message=$1
local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
echo "[$timestamp] $message" >> $LOG_FILE
}
# 主函数
main() {
case "$1" in
temp)
clean_temp_files
;;
logs)
clean_log_files
;;
packages)
clean_package_cache
;;
backups)
clean_old_backups "$2" "$3"
;;
cache)
clean_user_cache
;;
smart)
smart_clean "$2" "$3"
;;
all)
clean_temp_files
clean_log_files
clean_package_cache
clean_user_cache
;;
*)
echo "Usage: $0 {temp|logs|packages|backups|cache|smart|all}"
exit 1
;;
esac
}
main "$@"无敌#
磁盘空间预测系统#
#!/bin/bash
# 磁盘空间预测系统
METRICS_DB="/var/lib/disk_predictor/metrics.db"
PREDICTION_DIR="/var/lib/disk_predictor/predictions"
mkdir -p $(dirname $METRICS_DB) $PREDICTION_DIR
# 收集磁盘使用数据
collect_disk_data() {
local mount_point=$1
local timestamp=$(date +%s)
local total=$(df -h $mount_point | awk 'NR==2 {print $2}')
local used=$(df -h $mount_point | awk 'NR==2 {print $3}')
local avail=$(df -h $mount_point | awk 'NR==2 {print $4}')
local percent=$(df -h $mount_point | awk 'NR==2 {print $5}' | cut -d'%' -f1)
local data_file="$METRICS_DB/${mount_point//\//_}.csv"
echo "$timestamp,$total,$used,$avail,$percent" >> $data_file
}
# 预测磁盘空间
predict_disk_space() {
local mount_point=$1
local days=${2:-30}
local data_file="$METRICS_DB/${mount_point//\//_}.csv"
if [ ! -f "$data_file" ]; then
echo "No data available for $mount_point"
return 1
fi
echo "=== Disk Space Prediction for $mount_point ==="
echo "Prediction period: $days days"
echo ""
# 计算平均增长率
local current_usage=$(tail -1 $data_file | cut -d, -f5)
local start_usage=$(head -1 $data_file | cut -d, -f5)
local data_points=$(wc -l < $data_file)
local growth_rate=$(echo "scale=2; ($current_usage - $start_usage) / $data_points" | bc)
echo "Current usage: ${current_usage}%"
echo "Average growth rate: ${growth_rate}% per data point"
echo ""
# 预测未来使用情况
echo "Future predictions:"
for ((i=1; i<=$days; i++)); do
local predicted_usage=$(echo "scale=2; $current_usage + ($growth_rate * $i)" | bc)
local future_date=$(date -d "+$i days" '+%Y-%m-%d')
echo " $future_date: ${predicted_usage}%"
if (( $(echo "$predicted_usage >= 100" | bc -l) )); then
echo " ⚠️ WARNING: Disk will be full!"
fi
done
# 保存预测结果
local prediction_file="$PREDICTION_DIR/${mount_point//\//_}_$(date +%Y%m%d).txt"
{
echo "Disk Space Prediction - $(date)"
echo "Mount point: $mount_point"
echo "Prediction period: $days days"
echo ""
echo "Current usage: ${current_usage}%"
echo "Average growth rate: ${growth_rate}% per data point"
echo ""
echo "Future predictions:"
for ((i=1; i<=$days; i++)); do
local predicted_usage=$(echo "scale=2; $current_usage + ($growth_rate * $i)" | bc)
local future_date=$(date -d "+$i days" '+%Y-%m-%d')
echo " $future_date: ${predicted_usage}%"
done
} > $prediction_file
echo ""
echo "Prediction saved to: $prediction_file"
}
# 分析磁盘使用趋势
analyze_disk_trend() {
local mount_point=$1
local days=${2:-7}
local data_file="$METRICS_DB/${mount_point//\//_}.csv"
if [ ! -f "$data_file" ]; then
echo "No data available for $mount_point"
return 1
fi
echo "=== Disk Usage Trend for $mount_point ==="
echo "Last $days days"
echo ""
local end_time=$(date +%s)
local start_time=$((end_time - (days * 86400)))
tail -100 $data_file | awk -F, -v start=$start_time -v end=$end_time '$1 >= start && $1 <= end' | while read line; do
local timestamp=$(echo $line | cut -d, -f1)
local used=$(echo $line | cut -d, -f3)
local percent=$(echo $line | cut -d, -f5)
local formatted_time=$(date -d @$timestamp '+%Y-%m-%d %H:%M:%S')
echo "$formatted_time - Used: $used (${percent}%)"
done
}
# 生成预测报告
generate_prediction_report() {
local report_file="$PREDICTION_DIR/prediction_report_$(date +%Y%m%d).txt"
echo "Disk Space Prediction Report - $(date +%Y-%m-%d)" > $report_file
echo "=================================" >> $report_file
echo "" >> $report_file
# 当前磁盘使用情况
echo "=== Current Disk Usage ===" >> $report_file
df -h >> $report_file
echo "" >> $report_file
# 预测结果
echo "=== Predictions ===" >> $report_file
for mount_point in $(df | awk 'NR>1 {print $6}'); do
predict_disk_space $mount_point 30 >> $report_file
echo "" >> $report_file
done
echo "Prediction report saved to: $report_file"
}
# 主函数
main() {
case "$1" in
collect)
collect_disk_data "$2"
;;
predict)
predict_disk_space "$2" "$3"
;;
trend)
analyze_disk_trend "$2" "$3"
;;
report)
generate_prediction_report
;;
*)
echo "Usage: $0 {collect|predict|trend|report}"
exit 1
;;
esac
}
main "$@"磁盘容量规划系统#
#!/bin/bash
# 磁盘容量规划系统
CONFIG_FILE="/etc/disk_planner/config.conf"
PLAN_DIR="/var/lib/disk_planner/plans"
mkdir -p $PLAN_DIR
# 加载配置
source $CONFIG_FILE
# 分析磁盘使用模式
analyze_usage_pattern() {
local mount_point=$1
local days=${2:-30}
local data_file="/var/lib/disk_predictor/metrics/${mount_point//\//_}.csv"
if [ ! -f "$data_file" ]; then
echo "No data available for $mount_point"
return 1
fi
echo "=== Usage Pattern Analysis for $mount_point ==="
echo "Analysis period: $days days"
echo ""
# 计算统计信息
local min_usage=$(awk -F, 'NR>1 {print $5}' $data_file | sort -n | head -1)
local max_usage=$(awk -F, 'NR>1 {print $5}' $data_file | sort -n | tail -1)
local avg_usage=$(awk -F, 'NR>1 {sum+=$5; count++} END {print sum/count}' $data_file)
echo "Minimum usage: ${min_usage}%"
echo "Maximum usage: ${max_usage}%"
echo "Average usage: ${avg_usage}%"
echo ""
# 计算增长率
local current_usage=$(tail -1 $data_file | cut -d, -f5)
local start_usage=$(head -1 $data_file | cut -d, -f5)
local data_points=$(wc -l < $data_file)
local growth_rate=$(echo "scale=2; ($current_usage - $start_usage) / $data_points" | bc)
echo "Growth rate: ${growth_rate}% per data point"
echo ""
# 预测何时达到 100%
if (( $(echo "$growth_rate > 0" | bc -l) )); then
local days_to_full=$(echo "scale=0; (100 - $current_usage) / $growth_rate" | bc)
local full_date=$(date -d "+$days_to_full days" '+%Y-%m-%d')
echo "Predicted to be full in: $days_to_full days ($full_date)"
else
echo "Usage is stable or decreasing"
fi
}
# 生成容量规划建议
generate_capacity_recommendations() {
local mount_point=$1
local data_file="/var/lib/disk_predictor/metrics/${mount_point//\//_}.csv"
if [ ! -f "$data_file" ]; then
echo "No data available for $mount_point"
return 1
fi
echo "=== Capacity Recommendations for $mount_point ==="
echo ""
local current_usage=$(tail -1 $data_file | cut -d, -f5)
local growth_rate=$(awk -F, 'NR>1 {sum+=$5; count++} END {print (sum/count)}' $data_file)
# 基于当前使用情况给出建议
if [ $current_usage -lt 50 ]; then
echo "✓ Current usage is low (${current_usage}%)"
echo " No immediate action required"
elif [ $current_usage -lt 70 ]; then
echo "⚠️ Current usage is moderate (${current_usage}%)"
echo " Consider monitoring more closely"
echo " Plan for capacity expansion in 3-6 months"
elif [ $current_usage -lt 85 ]; then
echo "⚠️ Current usage is high (${current_usage}%)"
echo " Immediate action recommended:"
echo " 1. Clean up unnecessary files"
echo " 2. Implement data archiving"
echo " 3. Plan for capacity expansion in 1-3 months"
else
echo "🚨 Current usage is critical (${current_usage}%)"
echo " Urgent action required:"
echo " 1. Clean up unnecessary files immediately"
echo " 2. Implement data archiving immediately"
echo " 3. Plan for capacity expansion immediately"
fi
echo ""
# 基于增长率给出建议
local predicted_usage=$(echo "scale=2; $current_usage + ($growth_rate * 30)" | bc)
echo "Predicted usage in 30 days: ${predicted_usage}%"
if (( $(echo "$predicted_usage > 90" | bc -l) )); then
echo "⚠️ Disk will reach critical levels in 30 days"
echo " Consider immediate capacity expansion"
fi
}
# 生成容量规划报告
generate_capacity_plan() {
local report_file="$PLAN_DIR/capacity_plan_$(date +%Y%m%d).txt"
echo "Disk Capacity Plan - $(date +%Y-%m-%d)" > $report_file
echo "=====================" >> $report_file
echo "" >> $report_file
# 当前磁盘使用情况
echo "=== Current Disk Usage ===" >> $report_file
df -h >> $report_file
echo "" >> $report_file
# 使用模式分析
echo "=== Usage Pattern Analysis ===" >> $report_file
for mount_point in $(df | awk 'NR>1 {print $6}'); do
analyze_usage_pattern $mount_point 30 >> $report_file
echo "" >> $report_file
done
# 容量建议
echo "=== Capacity Recommendations ===" >> $report_file
for mount_point in $(df | awk 'NR>1 {print $6}'); do
generate_capacity_recommendations $mount_point >> $report_file
echo "" >> $report_file
done
# 行动计划
echo "=== Action Plan ===" >> $report_file
echo "Immediate actions (0-7 days):" >> $report_file
echo "- Review and clean up unnecessary files" >> $report_file
echo "- Implement log rotation policies" >> $report_file
echo "" >> $report_file
echo "Short-term actions (7-30 days):" >> $report_file
echo "- Implement data archiving" >> $report_file
echo "- Review and optimize storage usage" >> $report_file
echo "" >> $report_file
echo "Long-term actions (30+ days):" >> $report_file
echo "- Plan for capacity expansion" >> $report_file
echo "- Implement storage tiering" >> $report_file
echo "Capacity plan saved to: $report_file"
}
# 主函数
main() {
case "$1" in
analyze)
analyze_usage_pattern "$2" "$3"
;;
recommend)
generate_capacity_recommendations "$2"
;;
plan)
generate_capacity_plan
;;
*)
echo "Usage: $0 {analyze|recommend|plan}"
exit 1
;;
esac
}
main "$@"最佳实践#
- 定期检查磁盘空间:定期使用 df 检查磁盘空间使用情况
- 设置告警阈值:设置合理的告警阈值,及时发现问题
- 监控 inode 使用:不仅监控磁盘空间,还要监控 inode 使用情况
- 分析使用趋势:分析磁盘使用趋势,预测未来需求
- 及时清理:及时清理不必要的文件,释放磁盘空间
- 规划容量:根据使用趋势规划磁盘容量
- 使用人类可读格式:使用 -h 选项以人类可读格式显示
- 记录监控数据:定期记录监控数据,便于分析趋势
注意事项#
- df 显示的是文件系统的使用情况,不是物理磁盘的使用情况
- 虚拟文件系统(如 tmpfs)也会显示在 df 输出中
- inode 耗尽也会导致无法创建新文件
- 不同文件系统的使用情况可能不同
- 磁盘空间使用率接近 100% 时会影响系统性能
- 定期清理日志文件和临时文件
- 在生产环境中删除文件时要格外小心
- 注意备份重要数据后再进行清理
- 对于关键业务,建议使用专业的磁盘管理工具