free - Display Memory Usage

Monitor system memory and swap utilization

Command Overview

The free command displays the amount of free and used memory in the system, including physical RAM and swap space. It's one of the most essential commands for system monitoring and troubleshooting memory-related issues. The command reads information from /proc/meminfo and presents it in a readable format.

Basic Syntax

free [options]

Common Options:

  • -h, --human - Human-readable output (KB, MB, GB)
  • -b, --bytes - Display in bytes
  • -k, --kibi - Display in kibibytes (default)
  • -m, --mebi - Display in mebibytes
  • -g, --gibi - Display in gibibytes
  • -s N, --seconds N - Repeat every N seconds
  • -c N, --count N - Display N times
  • -t, --total - Show total for RAM + swap
  • -w, --wide - Wide output (separate buffers/cache)

Understanding Memory Columns

Column Description
total Total installed memory (excluding small reserved bits)
used Memory in use (total - free - buffers - cache)
free Unused memory (completely free, not allocated)
shared Memory used by tmpfs (shared memory)
buff/cache Memory used for buffers and cache (reclaimable)
available Estimate of memory available for starting new applications

Detailed Examples

Example 1

Basic Memory Display

Viewing system memory in default format:

$ free
               total        used        free      shared  buff/cache   available
Mem:        16384000     8192000     2048000      512000     6144000    7340000
Swap:        4096000      102400     3993600

Explanation: Default output shows memory in kibibytes. The Mem row shows physical RAM, while Swap row shows swap space. The available column is the most important - it shows how much memory is actually available for new applications.

Important: Don't be alarmed by low "free" values! Linux uses free memory for caching to improve performance. The "available" column is what really matters for determining if you need more RAM.
Example 2

Human-Readable Format

Displaying memory in human-readable units:

$ free -h
               total        used        free      shared  buff/cache   available
Mem:            16Gi        8.0Gi       2.0Gi       500Mi       6.0Gi       7.2Gi
Swap:          4.0Gi        100Mi       3.9Gi

Explanation: The -h flag automatically scales units to KB, MB, GB, or TB for easy reading. This is the most commonly used format for quick visual checks.

Tip: The -h option is usually the best choice for daily monitoring as it's immediately readable without mental math.
Example 3

Continuous Memory Monitoring

Watching memory usage in real-time:

$ free -h -s 2
               total        used        free      shared  buff/cache   available
Mem:            16Gi        8.0Gi       2.0Gi       500Mi       6.0Gi       7.2Gi
Swap:          4.0Gi        100Mi       3.9Gi

# Updates every 2 seconds...

               total        used        free      shared  buff/cache   available
Mem:            16Gi        8.2Gi       1.8Gi       500Mi       6.0Gi       7.0Gi
Swap:          4.0Gi        100Mi       3.9Gi

# Monitor 10 times with 3 second intervals
$ free -h -s 3 -c 10

Explanation: The -s option updates the display at specified intervals. -c limits the number of updates. This is useful for monitoring memory during specific operations or testing.

Tip: Use Ctrl+C to stop continuous monitoring. For more sophisticated monitoring, consider vmstat or htop.
Example 4

Wide Output Mode

Separating buffers and cache columns:

$ free -h -w
               total        used        free      shared     buffers       cache   available
Mem:            16Gi        8.0Gi       2.0Gi       500Mi       512Mi       5.5Gi       7.2Gi
Swap:          4.0Gi        100Mi       3.9Gi

Explanation: The -w option splits the buff/cache column into separate buffers and cache columns, providing more detailed information about how cached memory is being used.

Note: Buffers are used for block device I/O, while cache holds file system caches. Both can be reclaimed when applications need memory.
Example 5

Total Memory Summary

Displaying combined RAM and swap totals:

$ free -h -t
               total        used        free      shared  buff/cache   available
Mem:            16Gi        8.0Gi       2.0Gi       500Mi       6.0Gi       7.2Gi
Swap:          4.0Gi        100Mi       3.9Gi
Total:          20Gi        8.1Gi       5.9Gi

Explanation: The -t option adds a Total row that sums physical RAM and swap space, giving you the complete picture of virtual memory available to the system.

Example 6

Specific Unit Display

Displaying memory in specific units:

# Display in megabytes
$ free -m
               total        used        free      shared  buff/cache   available
Mem:           16384        8192        2048         500        6144        7340
Swap:           4096         100        3996

# Display in gigabytes
$ free -g
               total        used        free      shared  buff/cache   available
Mem:              16           8           2           0           6           7
Swap:              4           0           4

# Display in bytes (very detailed)
$ free -b
               total          used          free        shared    buff/cache     available
Mem:     16777216000    8388608000    2097152000     524288000    6291456000    7516192768
Swap:     4194304000      104857600    4089446400

Explanation: Use -m for megabytes, -g for gigabytes, or -b for exact byte counts. Choose based on your system size and precision needs.

Note: These options use binary units (1024-based): kibibytes (KiB), mebibytes (MiB), gibibytes (GiB), not decimal (1000-based) units.
Example 7

Memory Monitoring for Troubleshooting

Diagnosing memory pressure and swap usage:

# Check if system is swapping heavily
$ free -h
               total        used        free      shared  buff/cache   available
Mem:            16Gi         15Gi       100Mi       500Mi       900Mi       800Mi
Swap:          4.0Gi        3.5Gi       500Mi

# This output indicates memory pressure:
# - Low available memory (800Mi)
# - High swap usage (3.5Gi out of 4Gi)
# - System is likely experiencing performance issues

# Monitor swap activity over time
$ free -h -s 1 -c 60 | grep Swap

# Check swap usage percentage
$ free | awk '/Swap/ {printf "Swap: %.2f%% used\n", ($3/$2)*100}'
Swap: 87.50% used

Explanation: High swap usage combined with low available memory indicates memory pressure. The system is using slow disk-based swap instead of fast RAM. This typically causes performance degradation.

Warning: Consistent high swap usage (>50%) usually indicates you need more physical RAM or need to reduce running applications/services.
Example 8

Scripting and Automation

Using free in scripts for monitoring and alerts:

#!/bin/bash
# Memory monitoring script

# Get available memory in GB
AVAILABLE=$(free -g | awk '/Mem:/ {print $7}')
TOTAL=$(free -g | awk '/Mem:/ {print $2}')
PERCENT=$(echo "scale=2; ($AVAILABLE / $TOTAL) * 100" | bc)

echo "Available memory: ${AVAILABLE}GB out of ${TOTAL}GB (${PERCENT}%)"

# Alert if available memory is below 20%
if (( $(echo "$PERCENT < 20" | bc -l) )); then
    echo "WARNING: Low memory available!" | mail -s "Memory Alert" admin@example.com
fi

# Check swap usage
SWAP_TOTAL=$(free -m | awk '/Swap:/ {print $2}')
SWAP_USED=$(free -m | awk '/Swap:/ {print $3}')

if [ $SWAP_TOTAL -gt 0 ]; then
    SWAP_PERCENT=$(echo "scale=2; ($SWAP_USED / $SWAP_TOTAL) * 100" | bc)
    echo "Swap usage: ${SWAP_USED}MB out of ${SWAP_TOTAL}MB (${SWAP_PERCENT}%)"
    
    if (( $(echo "$SWAP_PERCENT > 50" | bc -l) )); then
        echo "WARNING: High swap usage detected!"
    fi
fi

Explanation: This script extracts memory metrics using awk and implements monitoring thresholds. It can be scheduled with cron for automated memory monitoring.

Tip: Use free with specific unit options (-m or -g) in scripts for consistent, parseable output.
Example 9

Comparing Memory States

Before and after analysis of memory usage:

# Capture memory state before starting application
$ free -h > /tmp/memory_before.txt

# Start memory-intensive application
$ ./large_application &

# Wait a few seconds
$ sleep 5

# Capture memory state after
$ free -h > /tmp/memory_after.txt

# Compare the two states
$ diff /tmp/memory_before.txt /tmp/memory_after.txt
3c3
> Mem:            16Gi        8.0Gi       6.0Gi       500Mi       1.5Gi       7.2Gi
---
< Mem:            16Gi         12Gi       2.0Gi       500Mi       1.5Gi       3.2Gi

# Shows 4GB more memory used by the application

# Or use watch for real-time comparison
$ watch -n 1 'free -h'

Explanation: Capturing memory states before and after operations helps identify memory leaks or determine application memory requirements. This is useful for capacity planning and troubleshooting.

Example 10

Advanced Memory Analysis

Deep dive into memory usage patterns:

# Detailed memory information with combined options
$ free -h -w -t
               total        used        free      shared     buffers       cache   available
Mem:            16Gi        8.0Gi       2.0Gi       500Mi       512Mi       5.0Gi       7.2Gi
Swap:          4.0Gi        100Mi       3.9Gi
Total:          20Gi        8.1Gi       5.9Gi

# Calculate memory usage percentage
$ free | awk '/Mem:/ {printf "Memory Usage: %.2f%%\n", ($3/$2) * 100}'
Memory Usage: 50.00%

# Calculate actual used memory (excluding cache/buffers)
$ free -h | awk '/Mem:/ {print "Actual Used (no cache): " $3}'
Actual Used (no cache): 8.0Gi

# Show memory with timestamps for logging
$ while true; do 
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $(free -h | grep Mem)"
    sleep 60
done >> /var/log/memory_monitor.log

# One-liner for memory percentage alert
$ free | awk '/Mem:/ {if (($3/$2)*100 > 80) print "Memory usage critical:", ($3/$2)*100"%"}'

# Export memory metrics in JSON format for monitoring tools
$ echo "{\"timestamp\": \"$(date -Iseconds)\", \"memory\": $(free -b | awk '/Mem:/ {printf "{\"total\":%s,\"used\":%s,\"free\":%s,\"available\":%s}", $2,$3,$4,$7}')}"
{"timestamp": "2025-01-15T10:30:00-05:00", "memory": {"total":16777216000,"used":8388608000,"free":2097152000,"available":7516192768}}

Explanation: These advanced techniques show how to extract specific metrics, create monitoring logs, and format output for integration with monitoring systems or dashboards.

Tip: For production monitoring, consider exporting free data to time-series databases like Prometheus or graphing tools like Graphite for historical analysis.

Understanding Memory Management in Linux

Memory Layout Visualization

Total Memory: 16 GB
┌─────────────────────────────────────────────────┐
│                                                 │
│  Applications Using Memory: 8 GB (Used)         │
│                                                 │
├─────────────────────────────────────────────────┤
│                                                 │
│  Buffers and Cache: 6 GB (Reclaimable)          │
│  (File system cache, disk buffers)              │
│                                                 │
├─────────────────────────────────────────────────┤
│                                                 │
│  Completely Free: 2 GB (Free)                   │
│                                                 │
└─────────────────────────────────────────────────┘

Available for Applications: 7.2 GB
(Free + Most of Cache/Buffers)
                

Key Memory Concepts

  • Cached Memory is NOT wasted: Linux uses free memory for caching to speed up file access. This cache is automatically reclaimed when applications need it.
  • "available" vs "free": The "available" column is more important than "free" - it includes cache that can be quickly reclaimed.
  • Swap is NOT always bad: Small amounts of swap usage are normal. Linux may swap out inactive pages. Heavy swap usage (>50%) indicates a problem.
  • Shared Memory: Memory used by tmpfs and shared between processes. Includes /dev/shm and shared memory segments.

Related Commands

Command Description Usage
vmstat Virtual memory statistics with more detail vmstat 1 10
top/htop Interactive process viewer with memory info htop
cat /proc/meminfo Detailed memory information source cat /proc/meminfo
smem Per-process memory reporting tool smem -k
ps aux Process memory usage ps aux --sort=-%mem
swapon -s Detailed swap space information swapon -s

Best Practices and Tips

Monitoring Best Practices

  • Use free -h for quick visual checks of memory status
  • Monitor the "available" column, not just "free"
  • Set up automated alerts when available memory drops below 20%
  • Check swap usage - consistent swap activity indicates RAM shortage
  • Use free -h -s 1 during performance testing to track memory changes
  • Log memory metrics regularly for trend analysis and capacity planning

Warning Signs

  • Available memory < 10%: Critical - applications may fail or be killed by OOM killer
  • Swap usage > 50%: System performance severely degraded
  • Rapidly increasing used memory: Possible memory leak
  • OOM (Out of Memory) events: Check dmesg | grep -i "out of memory"

Common Misconceptions

  • Myth: "Low free memory means I need more RAM"
    Reality: Linux uses spare memory for cache. Check "available" instead.
  • Myth: "Any swap usage means I need more RAM"
    Reality: Small swap usage is normal. Heavy, continuous swapping is the problem.
  • Myth: "Cache/buffers are wasted memory"
    Reality: They improve performance and are instantly reclaimed when needed.

Troubleshooting Memory Issues

Memory Pressure Investigation

# 1. Check current memory state
$ free -h

# 2. Identify memory-hungry processes
$ ps aux --sort=-%mem | head -20

# 3. Check for OOM killer activity
$ dmesg | grep -i "killed process"

# 4. Monitor swap activity
$ vmstat 1 10

# 5. Check for memory leaks (increasing RSS over time)
$ while true; do ps -p [PID] -o %mem,rss,vsz; sleep 5; done

# 6. Clear cache if needed (rarely necessary)
$ sudo sync; echo 3 | sudo tee /proc/sys/vm/drop_caches