free 命令详解#

free 是 Linux 系统中用于显示内存使用情况的命令。它可以显示系统内存和交换空间的总量、已用量、可用量和使用百分比,是系统管理员和开发人员进行内存管理的重要工具。

入门#

基本用法#

# 显示内存使用情况
free

# 以人类可读格式显示
free -h

# 显示特定单位
free -m

# 持续显示
free -s 5

常用选项#

选项说明
-h以人类可读格式显示(KB、MB、GB)
-b以字节为单位显示
-k以 KB 为单位显示(默认)
-m以 MB 为单位显示
-g以 GB 为单位显示
-s持续显示,指定间隔秒数
-c指定显示次数

基本示例#

# 显示内存使用情况
free

# 输出示例:
#               total        used        free      shared  buff/cache   available
# Mem:        8192000     4096000     2048000      512000     2048000     3072000
# Swap:       2048000           0     2048000

# 以人类可读格式显示
free -h

# 输出示例:
#               total        used        free      shared  buff/cache   available
# Mem:           7.8G        3.9G        2.0G        500M        2.0G        2.9G
# Swap:          2.0G          0B        2.0G

中级#

内存监控#

# 以 MB 为单位显示
free -m

# 以 GB 为单位显示
free -g

# 持续显示(每 5 秒更新一次)
free -s 5

# 显示 10 次
free -c 10

# 组合使用
free -h -s 5 -c 10

内存分析#

# 显示详细信息
free -h -w

# 显示低内存信息
free -l

# 显示总计
free -t

# 显示旧格式
free -o

# 显示宽格式
free -w

交换空间监控#

# 显示交换空间使用情况
free -h | grep Swap

# 监控交换空间使用
watch -n 5 'free -h | grep Swap'

# 检查交换空间是否在使用
free -h | awk '/Swap/ {print $3}'

高级#

高级选项#

# 显示总计
free -h -t

# 显示宽格式
free -h -w

# 显示低内存信息
free -h -l

# 显示旧格式
free -h -o

# 持续监控
free -h -s 1 -c 60

内存监控脚本#

#!/bin/bash
# 内存监控脚本

ALERT_THRESHOLD=80
ALERT_EMAIL="admin@example.com"

# 检查内存使用
check_memory_usage() {
    local threshold=$1
    
    local mem_total=$(free -m | awk '/Mem:/ {print $2}')
    local mem_used=$(free -m | awk '/Mem:/ {print $3}')
    local mem_percent=$(echo "scale=2; $mem_used * 100 / $mem_total" | bc)
    
    echo "Memory usage: ${mem_percent}%"
    
    if (( $(echo "$mem_percent > $threshold" | bc -l) )); then
        echo "ALERT: Memory usage high: ${mem_percent}%"
        echo "Memory usage high: ${mem_percent}%" | mail -s "Memory Alert" $ALERT_EMAIL
        return 1
    else
        return 0
    fi
}

# 检查交换空间使用
check_swap_usage() {
    local threshold=$1
    
    local swap_total=$(free -m | awk '/Swap:/ {print $2}')
    local swap_used=$(free -m | awk '/Swap:/ {print $3}')
    
    if [ $swap_total -eq 0 ]; then
        echo "No swap space configured"
        return 0
    fi
    
    local swap_percent=$(echo "scale=2; $swap_used * 100 / $swap_total" | bc)
    
    echo "Swap usage: ${swap_percent}%"
    
    if (( $(echo "$swap_percent > $threshold" | bc -l) )); then
        echo "ALERT: Swap usage high: ${swap_percent}%"
        echo "Swap usage high: ${swap_percent}%" | mail -s "Swap Alert" $ALERT_EMAIL
        return 1
    else
        return 0
    fi
}

# 生成内存报告
generate_memory_report() {
    local report_file="memory_report_$(date +%Y%m%d_%H%M%S).txt"
    
    echo "Memory Report - $(date)" > $report_file
    echo "===============" >> $report_file
    echo "" >> $report_file
    
    # 内存使用情况
    echo "=== Memory Usage ===" >> $report_file
    free -h >> $report_file
    echo "" >> $report_file
    
    # 详细信息
    echo "=== Detailed Memory Info ===" >> $report_file
    free -h -w >> $report_file
    echo "" >> $report_file
    
    # 总计
    echo "=== Total Memory ===" >> $report_file
    free -h -t >> $report_file
    
    echo "Report saved to: $report_file"
}

# 主函数
main() {
    case "$1" in
        check)
            check_memory_usage "$2"
            ;;
        swap)
            check_swap_usage "$2"
            ;;
        report)
            generate_memory_report
            ;;
        *)
            echo "Usage: $0 {check|swap|report}"
            exit 1
            ;;
    esac
}

main "$@"

内存分析工具#

#!/bin/bash
# 内存分析工具

# 分析内存使用
analyze_memory() {
    echo "=== Memory Analysis ==="
    echo ""
    
    # 总内存
    local mem_total=$(free -m | awk '/Mem:/ {print $2}')
    echo "Total memory: ${mem_total} MB"
    
    # 已用内存
    local mem_used=$(free -m | awk '/Mem:/ {print $3}')
    echo "Used memory: ${mem_used} MB"
    
    # 可用内存
    local mem_avail=$(free -m | awk '/Mem:/ {print $7}')
    echo "Available memory: ${mem_avail} MB"
    
    # 缓存内存
    local mem_cache=$(free -m | awk '/Mem:/ {print $6}')
    echo "Cached memory: ${mem_cache} MB"
    
    # 共享内存
    local mem_shared=$(free -m | awk '/Mem:/ {print $5}')
    echo "Shared memory: ${mem_shared} MB"
    
    # 使用百分比
    local mem_percent=$(echo "scale=2; $mem_used * 100 / $mem_total" | bc)
    echo "Memory usage: ${mem_percent}%"
}

# 分析交换空间
analyze_swap() {
    echo "=== Swap Analysis ==="
    echo ""
    
    # 总交换空间
    local swap_total=$(free -m | awk '/Swap:/ {print $2}')
    
    if [ $swap_total -eq 0 ]; then
        echo "No swap space configured"
        return
    fi
    
    echo "Total swap: ${swap_total} MB"
    
    # 已用交换空间
    local swap_used=$(free -m | awk '/Swap:/ {print $3}')
    echo "Used swap: ${swap_used} MB"
    
    # 可用交换空间
    local swap_free=$(free -m | awk '/Swap:/ {print $4}')
    echo "Free swap: ${swap_free} MB"
    
    # 使用百分比
    local swap_percent=$(echo "scale=2; $swap_used * 100 / $swap_total" | bc)
    echo "Swap usage: ${swap_percent}%"
}

# 查找高内存使用进程
find_high_memory_processes() {
    local threshold=${1:-5}
    
    echo "=== High Memory Processes (> ${threshold}%) ==="
    ps -eo pid,user,%mem,cmd --sort=-%mem | awk -v threshold=$threshold 'NR>1 && $3 > threshold {print $0}'
}

# 主函数
main() {
    case "$1" in
        analyze)
            analyze_memory
            ;;
        swap)
            analyze_swap
            ;;
        processes)
            find_high_memory_processes "$2"
            ;;
        *)
            echo "Usage: $0 {analyze|swap|processes}"
            exit 1
            ;;
    esac
}

main "$@"

大师#

企业级内存监控系统#

#!/bin/bash
# 企业级内存监控系统

CONFIG_FILE="/etc/memory_monitor/config.conf"
LOG_DIR="/var/log/memory_monitor"
METRICS_DB="/var/lib/memory_monitor/metrics.db"

mkdir -p $LOG_DIR $(dirname $METRICS_DB)

# 加载配置
source $CONFIG_FILE

# 收集内存指标
collect_memory_metrics() {
    local timestamp=$(date +%s)
    
    # 内存使用率
    local mem_total=$(free -m | awk '/Mem:/ {print $2}')
    local mem_used=$(free -m | awk '/Mem:/ {print $3}')
    local mem_percent=$(echo "scale=2; $mem_used * 100 / $mem_total" | bc)
    
    # 交换空间使用率
    local swap_total=$(free -m | awk '/Swap:/ {print $2}')
    local swap_used=$(free -m | awk '/Swap:/ {print $3}')
    local swap_percent=0
    
    if [ $swap_total -gt 0 ]; then
        swap_percent=$(echo "scale=2; $swap_used * 100 / $swap_total" | bc)
    fi
    
    # 保存到数据库
    echo "$timestamp,memory,$mem_percent,$mem_used,$mem_total" >> $METRICS_DB
    echo "$timestamp,swap,$swap_percent,$swap_used,$swap_total" >> $METRICS_DB
    
    # 检查告警阈值
    if (( $(echo "$mem_percent > $MEMORY_ALERT_THRESHOLD" | bc -l) )); then
        log_message "ALERT: Memory usage high: ${mem_percent}%"
        send_alert "Memory usage high: ${mem_percent}%"
    fi
    
    if (( $(echo "$swap_percent > $SWAP_ALERT_THRESHOLD" | bc -l) )); then
        log_message "ALERT: Swap usage high: ${swap_percent}%"
        send_alert "Swap usage high: ${swap_percent}%"
    fi
}

# 分析内存趋势
analyze_memory_trend() {
    local duration=$1
    
    local end_time=$(date +%s)
    local start_time=$((end_time - duration))
    
    echo "=== Memory Trend Analysis (last $duration seconds) ==="
    echo ""
    
    # 内存趋势
    echo "Memory Usage Trend:"
    grep ",memory," $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 percent=$(echo $line | cut -d, -f3)
        local used=$(echo $line | cut -d, -f4)
        local formatted_time=$(date -d @$timestamp '+%Y-%m-%d %H:%M:%S')
        
        echo "$formatted_time: ${percent}% (${used} MB)"
    done
    
    echo ""
    
    # 交换空间趋势
    echo "Swap Usage Trend:"
    grep ",swap," $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 percent=$(echo $line | cut -d, -f3)
        local used=$(echo $line | cut -d, -f4)
        local formatted_time=$(date -d @$timestamp '+%Y-%m-%d %H:%M:%S')
        
        echo "$formatted_time: ${percent}% (${used} MB)"
    done
}

# 生成监控报告
generate_monitor_report() {
    local report_file="$LOG_DIR/monitor_report_$(date +%Y%m%d).txt"
    
    echo "Memory Monitor Report - $(date +%Y-%m-%d)" > $report_file
    echo "=====================" >> $report_file
    echo "" >> $report_file
    
    # 当前内存使用情况
    echo "=== Current Memory Usage ===" >> $report_file
    free -h >> $report_file
    echo "" >> $report_file
    
    # 详细信息
    echo "=== Detailed Memory Info ===" >> $report_file
    free -h -w >> $report_file
    echo "" >> $report_file
    
    # 内存趋势
    echo "=== Memory Trends (last 24 hours) ===" >> $report_file
    analyze_memory_trend 86400 >> $report_file
    
    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 "Memory 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 "Memory Monitor started"
    
    while true; do
        collect_memory_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_memory_trend "$2"
            ;;
        report)
            generate_monitor_report
            ;;
        *)
            echo "Usage: $0 {monitor|analyze|report}"
            exit 1
            ;;
    esac
}

main "$@"

智能内存优化系统#

#!/bin/bash
# 智能内存优化系统

CONFIG_FILE="/etc/memory_optimizer/config.conf"
LOG_FILE="/var/log/memory_optimizer/optimizer.log"

mkdir -p $(dirname $LOG_FILE)

# 加载配置
source $CONFIG_FILE

# 清理页面缓存
clean_page_cache() {
    echo "Cleaning page cache..."
    
    sync
    echo 1 > /proc/sys/vm/drop_caches
    
    log_message "Page cache cleaned"
}

# 清理目录项和 inode 缓存
clean_dentries_inode() {
    echo "Cleaning dentries and inode cache..."
    
    sync
    echo 2 > /proc/sys/vm/drop_caches
    
    log_message "Dentries and inode cache cleaned"
}

# 清理所有缓存
clean_all_cache() {
    echo "Cleaning all caches..."
    
    sync
    echo 3 > /proc/sys/vm/drop_caches
    
    log_message "All caches cleaned"
}

# 优化交换空间
optimize_swap() {
    echo "Optimizing swap..."
    
    local swap_used=$(free -m | awk '/Swap:/ {print $3}')
    
    if [ $swap_used -gt 0 ]; then
        echo "Swap is in use, disabling..."
        swapoff -a
        sleep 5
        swapon -a
        
        log_message "Swap optimized"
    else
        echo "Swap is not in use"
    fi
}

# 调整 swappiness
adjust_swappiness() {
    local value=$1
    
    echo "Adjusting swappiness to $value..."
    
    echo $value > /proc/sys/vm/swappiness
    
    log_message "Swappiness adjusted to $value"
}

# 智能优化
smart_optimize() {
    local mem_percent=$(free -m | awk '/Mem:/ {print $3 * 100 / $2}')
    
    echo "Current memory usage: ${mem_percent}%"
    
    if (( $(echo "$mem_percent > 90" | bc -l) )); then
        echo "Memory usage critical, performing full optimization..."
        clean_all_cache
        optimize_swap
    elif (( $(echo "$mem_percent > 80" | bc -l) )); then
        echo "Memory usage high, performing partial optimization..."
        clean_page_cache
    else
        echo "Memory usage normal, no optimization needed"
    fi
}

# 查找高内存使用进程
find_high_memory_processes() {
    local threshold=${1:-5}
    
    echo "=== High Memory Processes (> ${threshold}%) ==="
    ps -eo pid,user,%mem,cmd --sort=-%mem | awk -v threshold=$threshold 'NR>1 && $3 > threshold {print $0}'
}

# 生成优化报告
generate_optimization_report() {
    local report_file="/var/log/memory_optimizer/optimization_report_$(date +%Y%m%d).txt"
    
    echo "Memory Optimization Report - $(date +%Y-%m-%d)" > $report_file
    echo "============================" >> $report_file
    echo "" >> $report_file
    
    # 当前内存使用情况
    echo "=== Current Memory Usage ===" >> $report_file
    free -h >> $report_file
    echo "" >> $report_file
    
    # 高内存使用进程
    echo "=== High Memory Processes ===" >> $report_file
    find_high_memory_processes 5 >> $report_file
    echo "" >> $report_file
    
    # 优化建议
    echo "=== Optimization Recommendations ===" >> $report_file
    echo "1. Clean page cache periodically" >> $report_file
    echo "2. Adjust swappiness value" >> $report_file
    echo "3. Monitor swap usage" >> $report_file
    echo "4. Optimize application memory usage" >> $report_file
    
    log_message "Optimization report generated: $report_file"
}

# 记录日志
log_message() {
    local message=$1
    local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    echo "[$timestamp] $message" >> $LOG_FILE
}

# 主函数
main() {
    case "$1" in
        page-cache)
            clean_page_cache
            ;;
        dentries)
            clean_dentries_inode
            ;;
        all)
            clean_all_cache
            ;;
        swap)
            optimize_swap
            ;;
        swappiness)
            adjust_swappiness "$2"
            ;;
        smart)
            smart_optimize
            ;;
        processes)
            find_high_memory_processes "$2"
            ;;
        report)
            generate_optimization_report
            ;;
        *)
            echo "Usage: $0 {page-cache|dentries|all|swap|swappiness|smart|processes|report}"
            exit 1
            ;;
    esac
}

main "$@"

无敌#

内存预测系统#

#!/bin/bash
# 内存预测系统

METRICS_DB="/var/lib/memory_predictor/metrics.db"
PREDICTION_DIR="/var/lib/memory_predictor/predictions"

mkdir -p $(dirname $METRICS_DB) $PREDICTION_DIR

# 收集内存使用数据
collect_memory_data() {
    local timestamp=$(date +%s)
    
    local mem_total=$(free -m | awk '/Mem:/ {print $2}')
    local mem_used=$(free -m | awk '/Mem:/ {print $3}')
    local mem_percent=$(echo "scale=2; $mem_used * 100 / $mem_total" | bc)
    
    local swap_total=$(free -m | awk '/Swap:/ {print $2}')
    local swap_used=$(free -m | awk '/Swap:/ {print $3}')
    local swap_percent=0
    
    if [ $swap_total -gt 0 ]; then
        swap_percent=$(echo "scale=2; $swap_used * 100 / $swap_total" | bc)
    fi
    
    echo "$timestamp,$mem_percent,$mem_used,$mem_total,$swap_percent,$swap_used,$swap_total" >> $METRICS_DB
}

# 预测内存使用
predict_memory_usage() {
    local days=${1:-30}
    
    if [ ! -f "$METRICS_DB" ]; then
        echo "No data available for prediction"
        return 1
    fi
    
    echo "=== Memory Usage Prediction ==="
    echo "Prediction period: $days days"
    echo ""
    
    # 计算平均增长率
    local current_usage=$(tail -1 $METRICS_DB | cut -d, -f2)
    local start_usage=$(head -1 $METRICS_DB | cut -d, -f2)
    local data_points=$(wc -l < $METRICS_DB)
    
    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: Memory will be full!"
        fi
    done
    
    # 保存预测结果
    local prediction_file="$PREDICTION_DIR/memory_prediction_$(date +%Y%m%d).txt"
    {
        echo "Memory Usage Prediction - $(date)"
        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_memory_trend() {
    local days=${1:-7}
    
    if [ ! -f "$METRICS_DB" ]; then
        echo "No data available for analysis"
        return 1
    fi
    
    echo "=== Memory Usage Trend ==="
    echo "Last $days days"
    echo ""
    
    local end_time=$(date +%s)
    local start_time=$((end_time - (days * 86400)))
    
    tail -100 $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 percent=$(echo $line | cut -d, -f2)
        local used=$(echo $line | cut -d, -f3)
        local formatted_time=$(date -d @$timestamp '+%Y-%m-%d %H:%M:%S')
        
        echo "$formatted_time - Usage: ${percent}% (${used} MB)"
    done
}

# 生成预测报告
generate_prediction_report() {
    local report_file="$PREDICTION_DIR/prediction_report_$(date +%Y%m%d).txt"
    
    echo "Memory Prediction Report - $(date +%Y-%m-%d)" > $report_file
    echo "=========================" >> $report_file
    echo "" >> $report_file
    
    # 当前内存使用情况
    echo "=== Current Memory Usage ===" >> $report_file
    free -h >> $report_file
    echo "" >> $report_file
    
    # 预测结果
    echo "=== Predictions ===" >> $report_file
    predict_memory_usage 30 >> $report_file
    echo "" >> $report_file
    
    # 趋势分析
    echo "=== Trend Analysis ===" >> $report_file
    analyze_memory_trend 7 >> $report_file
    
    echo "Prediction report saved to: $report_file"
}

# 主函数
main() {
    case "$1" in
        collect)
            collect_memory_data
            ;;
        predict)
            predict_memory_usage "$2"
            ;;
        trend)
            analyze_memory_trend "$2"
            ;;
        report)
            generate_prediction_report
            ;;
        *)
            echo "Usage: $0 {collect|predict|trend|report}"
            exit 1
            ;;
    esac
}

main "$@"

内存容量规划系统#

#!/bin/bash
# 内存容量规划系统

CONFIG_FILE="/etc/memory_planner/config.conf"
PLAN_DIR="/var/lib/memory_planner/plans"

mkdir -p $PLAN_DIR

# 加载配置
source $CONFIG_FILE

# 分析内存使用模式
analyze_usage_pattern() {
    local days=${1:-30}
    
    local data_file="/var/lib/memory_predictor/metrics.db"
    
    if [ ! -f "$data_file" ]; then
        echo "No data available for analysis"
        return 1
    fi
    
    echo "=== Memory Usage Pattern Analysis ==="
    echo "Analysis period: $days days"
    echo ""
    
    # 计算统计信息
    local min_usage=$(awk -F, 'NR>1 {print $2}' $data_file | sort -n | head -1)
    local max_usage=$(awk -F, 'NR>1 {print $2}' $data_file | sort -n | tail -1)
    local avg_usage=$(awk -F, 'NR>1 {sum+=$2; 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, -f2)
    local start_usage=$(head -1 $data_file | cut -d, -f2)
    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 data_file="/var/lib/memory_predictor/metrics.db"
    
    if [ ! -f "$data_file" ]; then
        echo "No data available for recommendations"
        return 1
    fi
    
    echo "=== Memory Capacity Recommendations ==="
    echo ""
    
    local current_usage=$(tail -1 $data_file | cut -d, -f2)
    local growth_rate=$(awk -F, 'NR>1 {sum+=$2; 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 memory expansion in 3-6 months"
    elif [ $current_usage -lt 85 ]; then
        echo "⚠️  Current usage is high (${current_usage}%)"
        echo "  Immediate action recommended:"
        echo "  1. Optimize application memory usage"
        echo "  2. Clean up unnecessary processes"
        echo "  3. Plan for memory expansion in 1-3 months"
    else
        echo "🚨 Current usage is critical (${current_usage}%)"
        echo "  Urgent action required:"
        echo "  1. Optimize application memory usage immediately"
        echo "  2. Clean up unnecessary processes immediately"
        echo "  3. Plan for memory 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 "⚠️  Memory will reach critical levels in 30 days"
        echo "  Consider immediate memory expansion"
    fi
}

# 生成容量规划报告
generate_capacity_plan() {
    local report_file="$PLAN_DIR/capacity_plan_$(date +%Y%m%d).txt"
    
    echo "Memory Capacity Plan - $(date +%Y-%m-%d)" > $report_file
    echo "=====================" >> $report_file
    echo "" >> $report_file
    
    # 当前内存使用情况
    echo "=== Current Memory Usage ===" >> $report_file
    free -h >> $report_file
    echo "" >> $report_file
    
    # 使用模式分析
    echo "=== Usage Pattern Analysis ===" >> $report_file
    analyze_usage_pattern 30 >> $report_file
    echo "" >> $report_file
    
    # 容量建议
    echo "=== Capacity Recommendations ===" >> $report_file
    generate_capacity_recommendations >> $report_file
    echo "" >> $report_file
    
    # 行动计划
    echo "=== Action Plan ===" >> $report_file
    echo "Immediate actions (0-7 days):" >> $report_file
    echo "- Review and optimize application memory usage" >> $report_file
    echo "- Clean up unnecessary processes" >> $report_file
    echo "" >> $report_file
    echo "Short-term actions (7-30 days):" >> $report_file
    echo "- Implement memory optimization policies" >> $report_file
    echo "- Review and optimize swap configuration" >> $report_file
    echo "" >> $report_file
    echo "Long-term actions (30+ days):" >> $report_file
    echo "- Plan for memory expansion" >> $report_file
    echo "- Implement memory monitoring and alerting" >> $report_file
    
    echo "Capacity plan saved to: $report_file"
}

# 主函数
main() {
    case "$1" in
        analyze)
            analyze_usage_pattern "$2"
            ;;
        recommend)
            generate_capacity_recommendations
            ;;
        plan)
            generate_capacity_plan
            ;;
        *)
            echo "Usage: $0 {analyze|recommend|plan}"
            exit 1
            ;;
    esac
}

main "$@"

最佳实践#

  1. 定期监控内存使用:定期使用 free 检查内存使用情况
  2. 设置告警阈值:设置合理的告警阈值,及时发现问题
  3. 关注交换空间使用:监控交换空间使用情况
  4. 分析内存趋势:分析内存使用趋势,预测未来需求
  5. 优化内存使用:优化应用程序的内存使用
  6. 合理配置 swappiness:根据系统需求调整 swappiness 值
  7. 使用人类可读格式:使用 -h 选项以人类可读格式显示
  8. 记录监控数据:定期记录监控数据,便于分析趋势

注意事项#

  • free 显示的内存使用情况包括缓存和缓冲区
  • Linux 系统会尽可能使用空闲内存作为缓存
  • 可用内存(available)比空闲内存(free)更能反映实际可用内存
  • 交换空间的使用通常表示内存不足
  • 频繁的交换空间使用会影响系统性能
  • 清理缓存可能会影响系统性能
  • 在生产环境中调整内存参数时要格外小心
  • 注意应用程序的内存使用情况
  • 对于关键业务,建议使用专业的内存管理工具