Innovate | Connect | Transform
ContactService statusUSD $

GICT knowledge base

How to View and Monitor Memory Usage in Linux

Published

Linux and Commands

Introduction

Memory monitoring is essential for maintaining optimal Linux system performance. Understanding RAM usage, swap space, and cache helps prevent slowdowns, crashes, and system freezes that impact productivity.

Linux uses sophisticated memory management that can seem confusing—high memory usage might actually indicate good performance through effective caching. This guide teaches you practical methods to monitor memory usage, identify resource-hungry processes, and maintain system health through effective memory management.

Why Memory Monitoring Is Essential

Memory monitoring is crucial for system performance and stability:

  • Performance Optimization: When RAM is exhausted, systems use slower swap space, dramatically reducing performance. Monitoring prevents these bottlenecks.
  • Troubleshooting: Identifies memory leaks and resource-intensive applications before they cause crashes or slowdowns.
  • Capacity Planning: Understanding usage patterns helps determine when RAM upgrades are needed.
  • Security: Unusual memory usage can indicate malware or unauthorized processes running on your system.
  • Cost Management: In cloud environments, accurate monitoring prevents over-provisioning expensive RAM resources.

Prerequisites and System Requirements

Memory monitoring requires minimal setup and works on all Linux distributions:

  • System Access: Terminal access (local or SSH). Most commands work with regular user privileges.
  • Compatible Systems: Works on Ubuntu, Debian, CentOS, RHEL, Fedora, Arch Linux, and all major distributions.
  • Built-in Tools: Core commands are pre-installed. Optional tools like htop or glances may need installation.
  • Basic Knowledge: Understanding of command-line basics is helpful but not required—we’ll explain each command clearly.

Comprehensive Step-by-Step Memory Monitoring Guide

Method 1: Using the free Command

The free command is the most fundamental tool for checking memory usage:

free

Basic output shows memory in kilobytes:

              total        used        free      shared  buff/cache   available
Mem:        8165264     2134567     1234567      123456     4796130     5698123
Swap:       2097148           0     2097148

For human-readable output:

free -h

Output with appropriate units (KB, MB, GB):

              total        used        free      shared  buff/cache   available
Mem:          7.8Gi       2.0Gi       1.2Gi       120Mi       4.6Gi       5.4Gi
Swap:         2.0Gi          0B       2.0Gi

Understanding the output:

  • total: Total physical RAM
  • used: Memory currently used by processes
  • free: Completely unused memory
  • shared: Memory used by shared libraries
  • buff/cache: Memory used for buffers and cache (can be freed if needed)
  • available: Memory available for new processes (free + reclaimable cache)

Continuous monitoring:

# Update every 2 seconds
free -h -s 2  
# Show 5 updates, 3 seconds apart
free -h -s 3 -c 5

Method 2: Examining /proc/meminfo

The /proc/meminfo file contains detailed memory statistics directly from the kernel:

cat /proc/meminfo

Key fields to monitor:

# Extract specific memory information
grep -E "(MemTotal|MemFree|MemAvailable|Buffers|Cached|SwapTotal|SwapFree)" /proc/meminfo

Create a custom memory summary:

#!/bin/bash
echo "=== Memory Summary ==="
awk '/MemTotal/ {total=$2}
      /MemFree/ {free=$2}
      /MemAvailable/ {available=$2}
      /Buffers/ {buffers=$2}
      /Cached/ {cached=$2}
      /SwapTotal/ {swap_total=$2}
      /SwapFree/ {swap_free=$2}
      END {
        used = total - free
        swap_used = swap_total - swap_free
        printf "Total RAM: %.1f GB\n", total/1024/1024
        printf "Used RAM: %.1f GB (%.1f%%)\n", used/1024/1024, (used/total)*100
        printf "Available RAM: %.1f GB\n", available/1024/1024
        printf "Buffers/Cache: %.1f GB\n", (buffers+cached)/1024/1024
        printf "Swap Used: %.1f GB / %.1f GB\n", swap_used/1024/1024, swap_total/1024/1024
      }' /proc/meminfo

Method 3: Using top Command

The top command shows real-time memory usage along with process information:

top

Key memory lines in top output:

  • KiB Mem: Physical memory usage
  • KiB Swap: Swap space usage

For memory-focused display:

# Sort by memory usage
top -o %MEM  
# Batch mode for scripting
top -b -n 1 | head -20

Extract memory info from top:

top -b -n 1 | grep -E "(KiB Mem|KiB Swap)"

Method 4: Using htop (Enhanced Interactive Monitor)

Install and use htop for improved visualization:

# Ubuntu/Debian
sudo apt install htop
# CentOS/RHEL/Fedora
sudo yum install htop
# or
sudo dnf install htop
# Run htop
htop

htop provides:

  • Color-coded memory and swap bars
  • Tree view of processes
  • Easy sorting by memory usage
  • Interactive process management

Method 5: Process-Specific Memory Analysis

Using ps command for memory details:

# Show memory usage for all processes
ps aux --sort=-%mem | head -20  
# Show specific memory columns
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head -20  
# Memory usage in MB
ps -eo pid,cmd,size,rss | head -20

Understanding ps memory columns:

  • %MEM: Percentage of physical memory used
  • VSZ: Virtual memory size (total virtual memory used)
  • RSS: Resident Set Size (physical memory currently used)
  • SIZE: Virtual image size

Using pmap for detailed process memory mapping:

# Show memory map for specific process (replace PID)
pmap -d 1234  
# Show memory map with human-readable sizes
pmap -x 1234

Method 6: Using vmstat for System Memory Statistics

The vmstat command shows virtual memory statistics:

# Basic memory statistics
vmstat  
# Update every 2 seconds, 5 times
vmstat 2 5  
# Memory statistics in MB
vmstat -S M

Key vmstat memory columns:

  • free: Free memory
  • buff: Buffer memory
  • cache: Cache memory
  • si/so: Swap in/out per second

Method 7: Advanced Memory Monitoring with /proc/PID/status

Check memory usage for specific processes:

# Function to get process memory info
get_process_memory() {
    local pid=$1
    local process_name=$(ps -p $pid -o comm= 2>/dev/null)
    if [ -n "$process_name" ]; then
        echo "=== Memory info for $process_name (PID: $pid) ==="
        grep -E "(VmSize|VmRSS|VmData|VmStk|VmExe|VmLib)" /proc/$pid/status 2>/dev/null
    else
        echo "Process with PID $pid not found"
    fi
}
# Usage: get_process_memory 1234

Method 8: Creating Comprehensive Memory Monitoring Scripts

Real-time memory monitor:

#!/bin/bash
# Memory monitoring script
monitor_memory() {
    while true; do
        clear
        echo "=== Linux Memory Monitor - $(date) ==="
        echo ""
        
        # Basic memory info
        echo "Memory Usage:"
        free -h
        echo ""
        
        # Top memory-consuming processes
        echo "Top 10 Memory-Consuming Processes:"
        ps aux --sort=-%mem --no-headers | head -10 | awk '{printf "%-8s %-6s %-6s %-15s %s\n", $1, $2, $4, $11, $12}'
        echo ""
        
        # Memory usage percentage
        MEMORY_USAGE=$(free | grep Mem | awk '{printf "%.1f", ($3/$2) * 100.0}')
        SWAP_USAGE=$(free | grep Swap | awk '{if($2>0) printf "%.1f", ($3/$2) * 100.0; else print "0.0"}')
        
        echo "Memory Usage: ${MEMORY_USAGE}%"
        echo "Swap Usage: ${SWAP_USAGE}%"
        
        # Warning thresholds
        if (( $(echo "$MEMORY_USAGE > 80" | bc -l) )); then
            echo "WARNING: High memory usage detected!"
        fi
        
        if (( $(echo "$SWAP_USAGE > 20" | bc -l) )); then
            echo "WARNING: Swap usage detected - consider adding RAM!"
        fi
        
        echo ""
        echo "Press Ctrl+C to stop monitoring"
        sleep 5
    done
}
monitor_memory

Memory logging script:

#!/bin/bash
LOG_FILE="/var/log/memory-usage.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Function to log memory statistics
log_memory() {
    local mem_info=$(free -m | grep "Mem:" | awk '{printf "Total: %dMB, Used: %dMB (%.1f%%), Available: %dMB", $2, $3, ($3/$2)*100, $7}')
    local swap_info=$(free -m | grep "Swap:" | awk '{if($2>0) printf "Swap Used: %dMB (%.1f%%)", $3, ($3/$2)*100; else printf "Swap: Not used"}')
    
    echo "$TIMESTAMP - $mem_info, $swap_info" >> $LOG_FILE
}
log_memory
# Add to crontab for regular logging:
# */5 * * * * /path/to/memory-log.sh

Method 9: Memory Usage Alerts and Automation

Memory alert script:

#!/bin/bash
MEMORY_THRESHOLD=85
SWAP_THRESHOLD=25
EMAIL="[email protected]"

# Get current memory usage percentage
MEMORY_USAGE=$(free | grep Mem | awk '{printf "%.0f", ($3/$2) * 100.0}')
SWAP_USAGE=$(free | grep Swap | awk '{if($2>0) printf "%.0f", ($3/$2) * 100.0; else print "0"}')

# Check memory threshold
if [ "$MEMORY_USAGE" -gt "$MEMORY_THRESHOLD" ]; then
    MESSAGE="High memory usage alert: ${MEMORY_USAGE}% used on $(hostname)"
    echo "$MESSAGE" | mail -s "Memory Alert" $EMAIL
    logger "Memory alert: $MEMORY_USAGE% usage"
fi

# Check swap threshold
if [ "$SWAP_USAGE" -gt "$SWAP_THRESHOLD" ]; then
    MESSAGE="High swap usage alert: ${SWAP_USAGE}% used on $(hostname)"
    echo "$MESSAGE" | mail -s "Swap Alert" $EMAIL
    logger "Swap alert: $SWAP_USAGE% usage"
fi

Method 10: Using Third-Party Monitoring Tools

Install and use glances:

# Ubuntu/Debian
sudo apt install glances
# CentOS/RHEL/Fedora
sudo yum install glances
# or
sudo dnf install glances
# Run glances
glances

Install and use atop:

# Ubuntu/Debian
sudo apt install atop
# Run atop with 2-second intervals
atop 2

Using sar (System Activity Reporter):

# Install sysstat package
sudo apt install sysstat
# Ubuntu/Debian
sudo yum install sysstat   # CentOS/RHEL
# Show memory statistics
sar -r 2 5  
# Show memory and swap usage
sar -S 2 5

Benefits of Systematic Memory Monitoring

Regular memory monitoring provides key advantages for system management:

  • Proactive Problem Prevention: Detect memory leaks and resource issues before they cause system crashes or performance problems.
  • Performance Optimization: Identify bottlenecks and optimize resource allocation for better system responsiveness.
  • Cost Savings: Right-size cloud instances and avoid over-provisioning expensive RAM resources.
  • Enhanced Security: Detect unusual memory patterns that might indicate malware or unauthorized processes.
  • Accurate Planning: Make data-driven decisions about hardware upgrades based on actual usage trends rather than guesswork.

Conclusion

Memory monitoring is fundamental to maintaining healthy Linux systems. The methods covered—from basic free commands to advanced monitoring scripts—give you the tools to understand and optimize memory usage effectively.

Regular monitoring helps prevent performance issues, identify problematic applications, and make informed decisions about system resources. Whether managing a desktop or server environment, these techniques will improve system stability and performance.

Start implementing these monitoring practices today. Create scripts for your specific needs, establish usage baselines, and set up alerts for critical thresholds. Proactive memory management leads to more reliable systems and better user experiences.

Related guides

Account services are unavailable until the production backend is configured.