Check Memory Usage with free Command - Linux Tutorial

Learn how to monitor system memory usage with the free command in Linux. Essential guide for system administrators and developers.

Check Memory Usage with free Command

Introduction

The free command is one of the most fundamental and widely used utilities in Linux and Unix-like operating systems for monitoring system memory usage. This command provides a comprehensive overview of both physical RAM and swap space utilization, making it an essential tool for system administrators, developers, and users who need to monitor system performance and troubleshoot memory-related issues.

Memory management is crucial for system performance, and understanding how memory is being utilized can help identify bottlenecks, optimize applications, and prevent system crashes due to memory exhaustion. The free command offers a quick and efficient way to obtain this critical information without requiring special privileges or complex configuration.

Command Syntax

The basic syntax for the free command is:

`bash free [options] `

The command can be executed without any options to display basic memory information, or various options can be added to customize the output format and update intervals.

Basic Usage

Simple Memory Check

The most basic usage of the free command involves running it without any arguments:

`bash free `

This command will display output similar to:

` total used free shared buff/cache available Mem: 8192000 2048000 3072000 256000 3072000 5632000 Swap: 2097152 0 2097152 `

Understanding the Output Columns

The output contains several important columns that provide detailed information about memory usage:

| Column | Description | |--------|-------------| | total | Total amount of physical RAM or swap space | | used | Amount of memory currently in use by applications | | free | Amount of completely unused memory | | shared | Memory used by tmpfs filesystems | | buff/cache | Memory used for buffers and cache | | available | Estimation of memory available for starting new applications |

Command Options and Flags

Display Options

#### Human Readable Format (-h)

The -h option displays memory sizes in human-readable format using appropriate units:

`bash free -h `

Output example: ` total used free shared buff/cache available Mem: 7.8G 2.0G 2.9G 250M 3.0G 5.4G Swap: 2.0G 0B 2.0G `

#### Bytes Format (-b)

Display memory information in bytes:

`bash free -b `

#### Kilobytes Format (-k)

Display memory information in kilobytes (default):

`bash free -k `

#### Megabytes Format (-m)

Display memory information in megabytes:

`bash free -m `

Output example: ` total used free shared buff/cache available Mem: 8000 2000 3000 250 3000 5500 Swap: 2048 0 2048 `

#### Gigabytes Format (-g)

Display memory information in gigabytes:

`bash free -g `

Continuous Monitoring Options

#### Continuous Updates (-s)

The -s option allows continuous monitoring by specifying the update interval in seconds:

`bash free -s 2 `

This command updates the memory information every 2 seconds, providing real-time monitoring capabilities.

#### Count Option (-c)

Specify the number of updates to display before exiting:

`bash free -s 1 -c 10 `

This command displays memory information 10 times with 1-second intervals between updates.

Additional Display Options

#### Wide Mode (-w)

The -w option provides wider output with separate columns for buffers and cache:

`bash free -w `

Output example: ` total used free shared buffers cache available Mem: 8192000 2048000 3072000 256000 512000 2560000 5632000 Swap: 2097152 0 2097152 `

#### Total Line (-t)

Display a line showing the total of physical memory and swap:

`bash free -t `

Output example: ` total used free shared buff/cache available Mem: 8192000 2048000 3072000 256000 3072000 5632000 Swap: 2097152 0 2097152 Total: 10289152 2048000 5169152 `

Detailed Memory Information Explanation

Physical Memory (RAM)

Physical memory represents the actual RAM installed in the system. Understanding each component is crucial for effective memory management:

#### Total Memory

The total column shows the complete amount of physical RAM available to the system. This value is typically slightly less than the installed RAM due to hardware reservations and kernel usage.

#### Used Memory

Used memory represents the amount of RAM currently allocated to running processes and system operations. This includes:

- Application memory usage - Kernel data structures - Device drivers - System processes

#### Free Memory

Free memory indicates completely unused RAM that is immediately available for new processes. In modern Linux systems, this value is often relatively small because the system efficiently uses available memory for caching.

#### Shared Memory

Shared memory refers to RAM used by tmpfs filesystems and inter-process communication mechanisms. This memory can be accessed by multiple processes simultaneously.

#### Buffer/Cache Memory

This represents memory used by the kernel for:

- Buffers: Temporary storage for data being written to or read from storage devices - Cache: Copies of files and data from storage devices kept in memory for faster access

#### Available Memory

Available memory is an estimate of how much memory is available for starting new applications without swapping. This calculation considers that some cached memory can be freed if needed.

Swap Space

Swap space serves as virtual memory extension when physical RAM becomes insufficient:

#### Swap Total

Total configured swap space, which can include swap partitions and swap files.

#### Swap Used

Amount of swap space currently in use. High swap usage often indicates insufficient physical memory.

#### Swap Free

Available swap space for future use.

Practical Examples and Use Cases

Example 1: Basic System Monitoring

`bash

Check current memory status

free -h

Monitor memory usage every 5 seconds

free -h -s 5

Check memory 3 times with 2-second intervals

free -h -s 2 -c 3 `

Example 2: Detailed Memory Analysis

`bash

Wide format with human-readable units

free -w -h

Include total line for comprehensive view

free -h -t

Continuous monitoring with detailed format

free -w -h -s 1 `

Example 3: Scripting and Automation

`bash

Extract specific values for scripting

total_mem=$(free -m | awk 'NR==2{print $2}') used_mem=$(free -m | awk 'NR==2{print $3}') available_mem=$(free -m | awk 'NR==2{print $7}')

echo "Total Memory: ${total_mem}MB" echo "Used Memory: ${used_mem}MB" echo "Available Memory: ${available_mem}MB" `

Memory Usage Interpretation

Healthy Memory Usage Patterns

| Scenario | Characteristics | Interpretation | |----------|----------------|----------------| | Normal Usage | Low swap usage, reasonable free memory | System operating efficiently | | Cache Heavy | High buff/cache, low free memory | Normal behavior, cache will be freed when needed | | Memory Pressure | High used memory, moderate swap usage | Monitor closely, consider adding RAM | | Critical State | Very high swap usage, minimal available memory | Immediate attention required |

Warning Signs

#### High Swap Usage

Consistent swap usage above 50% of total swap space may indicate:

- Insufficient physical RAM - Memory leaks in applications - Poorly optimized applications - Need for system upgrade

#### Low Available Memory

When available memory consistently falls below 10% of total memory:

- System performance may degrade - Applications may fail to start - Risk of out-of-memory conditions

#### Rapid Memory Growth

Monitoring memory usage over time can reveal:

- Memory leaks in applications - Runaway processes - System resource exhaustion

Advanced Usage Scenarios

Combining with Other Commands

#### Memory Usage by Process

`bash

Combine free with ps to get comprehensive memory view

free -h && echo "Top memory consumers:" && ps aux --sort=-%mem | head -10 `

#### System Resource Overview

`bash

Complete system resource check

echo "=== Memory Usage ===" && free -h && \ echo "=== Disk Usage ===" && df -h && \ echo "=== CPU Load ===" && uptime `

Automated Monitoring Scripts

#### Memory Alert Script

`bash #!/bin/bash THRESHOLD=90 USED_PERCENT=$(free | awk 'NR==2{printf "%.0f", $3*100/$2}')

if [ $USED_PERCENT -gt $THRESHOLD ]; then echo "WARNING: Memory usage is ${USED_PERCENT}%" free -h fi `

#### Memory Log Collection

`bash #!/bin/bash LOG_FILE="/var/log/memory_usage.log" while true; do echo "$(date): $(free -h | grep Mem:)" >> $LOG_FILE sleep 300 # Log every 5 minutes done `

Troubleshooting Common Issues

High Memory Usage

When encountering high memory usage:

1. Identify memory consumers: `bash ps aux --sort=-%mem | head -20 `

2. Check for memory leaks: `bash free -s 5 -c 12 # Monitor for 1 minute `

3. Analyze swap usage: `bash swapon --show `

System Performance Issues

For performance-related memory issues:

1. Monitor continuous usage: `bash watch -n 1 'free -h' `

2. Check memory pressure: `bash free -h && cat /proc/pressure/memory `

3. Examine kernel memory usage: `bash cat /proc/meminfo | grep -E "(Slab|PageTables|VmallocUsed)" `

Best Practices and Recommendations

Regular Monitoring

- Check memory usage during peak system load times - Monitor trends over time to identify patterns - Set up automated alerts for critical memory levels - Document baseline memory usage for comparison

Performance Optimization

- Understand that low free memory is normal in Linux systems - Focus on available memory rather than free memory - Consider the buff/cache memory as potentially available - Monitor swap usage as an indicator of memory pressure

System Administration

- Use human-readable format (-h) for easier interpretation - Combine free with other monitoring tools for comprehensive analysis - Create scripts for automated monitoring and alerting - Maintain logs of memory usage for historical analysis

Integration with System Monitoring

Log Analysis

Memory usage information can be integrated into system logs:

`bash

Add memory info to system logs

logger "Memory Status: $(free -h | grep Mem:)" `

Monitoring Tools Integration

The free command output can be parsed by monitoring tools:

- Nagios plugins - Zabbix monitoring - Prometheus exporters - Custom monitoring scripts

Conclusion

The free command is an indispensable tool for Linux system administration and monitoring. Its simplicity belies its power in providing crucial insights into system memory usage patterns. Understanding how to interpret its output and use its various options effectively enables system administrators to maintain optimal system performance, identify potential issues before they become critical, and make informed decisions about system resources.

Regular use of the free command, combined with other system monitoring tools, forms the foundation of effective system administration. Whether used for quick status checks, continuous monitoring, or automated alerting systems, the free command remains one of the most valuable utilities in the Linux toolkit.

By mastering the various options and understanding the nuances of memory management in Linux systems, administrators can ensure their systems operate efficiently and reliably. The key is not just knowing how to run the command, but understanding what the output means and how to act on that information to maintain system health and performance.

Tags

  • Command Line
  • Linux
  • System Monitoring
  • Unix
  • memory management

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Check Memory Usage with free Command - Linux Tutorial