CommandsLinux

Free Command on Linux with Examples

Free Command on Linux

Memory management is one of the most critical aspects of maintaining a healthy Linux system. Whether you’re a system administrator managing server resources or a developer troubleshooting application performance, understanding your system’s memory usage is essential. The free command is a powerful yet simple utility that provides valuable insights into memory allocation and utilization on Linux systems.

This comprehensive guide explores the free command’s capabilities, from basic usage to advanced techniques. You’ll learn how to interpret the command’s output, customize its display, and use it effectively for system monitoring and troubleshooting.

Understanding Linux Memory Concepts

Before diving into the free command itself, it’s important to understand some fundamental concepts about how Linux manages memory.

Physical vs. Virtual Memory

Linux uses a sophisticated memory management system that distinguishes between physical and virtual memory. Physical memory refers to the actual RAM installed in your computer. Virtual memory, on the other hand, is an abstraction that presents a contiguous address space to processes, regardless of where the data physically resides.

The kernel maps virtual memory addresses to physical memory locations, allowing processes to operate as if they have exclusive access to memory. This virtualization enables Linux to run more processes than would fit in physical RAM by utilizing swap space when necessary.

Memory Terminology

To fully understand the free command’s output, you need to be familiar with these key terms:

  • RAM (Random Access Memory): The physical memory hardware in your system
  • Swap space: Disk space used as virtual memory when physical RAM is full
  • Buffers: Memory used by the kernel to cache disk blocks
  • Cache: Memory used to store recently accessed file data
  • Shared memory: Memory segments that can be accessed by multiple processes

Memory States in Linux

Linux categorizes memory in several states:

  • Free memory: RAM that is completely unused and available
  • Used memory: RAM currently allocated to processes
  • Available memory: Memory that can be allocated to new processes without swapping
  • Cached memory: Previously used memory that can be quickly reclaimed if needed

Linux prioritizes memory efficiency by keeping recently accessed data in cache. This approach might make it appear as though you have less free memory than you actually do, but cached memory can be quickly repurposed when applications need it.

Basic Syntax and Usage of the free Command

Command Syntax

The basic syntax of the free command is straightforward:

free [OPTIONS]

When run without any options, the command provides a snapshot of your system’s memory usage in kibibytes (KiB).

Running the Basic Command

Let’s start with the most basic form of the command:

free

This displays a table showing the total, used, and free memory, along with details about shared memory, buffers/cache, and available memory. The output also includes information about your swap space usage.

Understanding Units of Measurement

By default, the free command displays memory values in kibibytes (KiB), which can be difficult to read on modern systems with gigabytes of RAM. The command supports various units of measurement to make the output more readable, which we’ll explore in the options section.

It’s worth noting that the free command gathers its information by parsing the /proc/meminfo file, which contains real-time data about your system’s memory usage.

Detailed Explanation of free Command Output

When you run the free command, it produces output similar to the following:

              total        used        free      shared  buff/cache   available
Mem:       16326428     7614148     4330644      460444     4377636     8083884
Swap:       2097148      132540     1964608

Header Row Elements

The columns in the output represent different aspects of memory usage:

  • total: The total amount of memory in the system
  • used: Memory currently being used by processes
  • free: Memory not currently in use
  • shared: Memory shared by multiple processes
  • buff/cache: Memory used for buffers and cache
  • available: Estimated memory available for new applications without swapping

Memory Row Analysis

The “Mem:” row provides information about your system’s physical RAM:

  • The “total” column shows the total amount of physical memory
  • The “used” column indicates memory allocated to running processes
  • The “free” column shows completely unused memory
  • The “shared” column displays memory shared between processes
  • The “buff/cache” column shows memory used by the kernel for buffers and cache
  • The “available” column estimates how much memory is available for starting new applications

The relationship between these values is important. For example, the sum of “used,” “free,” and “buff/cache” equals the “total” memory. The “available” memory is typically larger than “free” memory because it includes some of the “buff/cache” memory that can be reclaimed if needed.

Swap Row Interpretation

The “Swap:” row shows information about your swap space:

  • The “total” column shows the total swap space configured
  • The “used” column indicates how much swap space is currently in use
  • The “free” column shows unused swap space

High swap usage when plenty of physical memory is available could indicate a memory leak or poorly configured swappiness parameter. Conversely, some swap usage is normal and doesn’t necessarily indicate a problem.

Essential Options and Flags

The free command supports various options to customize its output and behavior. Here are the most useful ones:

Changing Display Units

To make the output more readable, you can specify different units:

  • -b or --bytes: Display in bytes
  • -k or --kibi: Display in kibibytes (default)
  • -m or --mebi: Display in mebibytes
  • -g or --gibi: Display in gibibytes
  • --tebi: Display in tebibytes
  • --pebi: Display in pebibytes
  • --si: Use powers of 1000 (KB, MB, GB) instead of powers of 1024 (KiB, MiB, GiB)

For example, to display memory in megabytes:

free -m

Customizing Output Format

These options help format the output for better readability:

  • -h or --human: Automatically scales units to the shortest three-digit form for human readability
  • -w or --wide: Displays buffers and cache separately in wide output
  • --iec: Uses IEC standard binary prefixes

The -h option is particularly useful as it automatically chooses the most appropriate unit for each value:

free -h

Controlling Display Behavior

The free command can continuously update its display at specified intervals:

  • -c [count] or --count [count]: Display the output a specified number of times
  • -s [seconds] or --seconds [delay]: Continuously update the display with the specified delay in seconds

For example, to update the display every 5 seconds:

free -s 5

Other Useful Options

Additional options provide more specialized information:

  • -t or --total: Display a line showing column totals
  • -l or --lohi: Show detailed low and high memory statistics
  • --help: Display help information
  • -V or --version: Show the program version

Practical Examples with Real-World Scenarios

Let’s explore some practical examples of how to use the free command in real-world scenarios.

Monitoring Memory in Human-Readable Format

The most common way to use the free command is with the human-readable option:

free -h

This command displays memory sizes using the most appropriate unit (KiB, MiB, GiB, etc.) for each value, making it much easier to interpret the output at a glance. This is particularly useful on systems with large amounts of RAM.

For example, the output might look like:

              total        used        free      shared  buff/cache   available
Mem:           15Gi       7.2Gi       4.1Gi       448Mi       4.1Gi       7.7Gi
Swap:          2.0Gi       129Mi       1.8Gi

Continuous Memory Monitoring

To monitor memory usage in real-time, use the -s option followed by the update interval in seconds:

free -s 5

This command refreshes the output every 5 seconds, allowing you to observe memory changes over time. This is particularly useful when monitoring resource usage during application testing or when troubleshooting memory leaks.

To stop the continuous display, press Ctrl+C.

Displaying Memory Multiple Times

If you want to limit the number of updates, combine the -c and -s options:

free -c 3 -s 2

This command displays the memory information three times with a 2-second interval between updates, then automatically exits. This approach is useful for scripting or when you need a quick series of snapshots without manual intervention.

Combining Multiple Options

You can combine multiple options to customize the output according to your needs:

free -ht

This command displays memory in human-readable format and includes a total line at the bottom. Combining options allows you to create a customized view that presents exactly the information you need in the most readable format.

Use Cases for System Administrators

System administrators can leverage the free command for various maintenance and monitoring tasks.

Detecting Memory Leaks

Memory leaks occur when programs continuously allocate memory but fail to release it properly. To detect potential memory leaks:

  1. Start monitoring with free -s 5 -h
  2. Observe the “used” memory column over time
  3. If used memory steadily increases without corresponding increases in system activity, you might have a memory leak
  4. Use additional tools like top or ps to identify which processes are consuming memory

Server Performance Optimization

The free command helps in making informed decisions about server configuration:

  1. Run free -h to assess your current memory usage
  2. If available memory is consistently low, consider adding more RAM or optimizing applications
  3. If swap usage is high despite available RAM, adjust the swappiness parameter
  4. Use the information to properly size containerized applications or virtual machines

Determining When to Add More RAM

Several metrics from the free command output can indicate insufficient memory:

  1. Low “available” memory (less than 10% of total) during normal operation
  2. Consistent swap usage despite having free memory
  3. Poor system performance correlated with high memory usage

When these signs appear consistently, it might be time to consider a memory upgrade for your system.

Troubleshooting Memory Issues

The free command is invaluable for diagnosing memory-related problems.

High Memory Usage Problems

If your system shows high memory usage:

  1. Check the “available” column, not just “free”
  2. Remember that Linux uses cache aggressively, which appears as used memory but can be released when needed
  3. If available memory is consistently low, use top or htop to identify memory-hungry processes
  4. Consider terminating unnecessary processes or optimizing applications to reduce memory consumption

Swap Usage Concerns

Excessive swap usage can severely impact system performance:

  1. If “used” swap is high but “available” RAM is also high, adjust the swappiness parameter
  2. If both swap and RAM are heavily used, you may need more physical memory
  3. Occasional swap usage is normal, especially on desktop systems that might go into sleep/hibernate states
  4. To reduce swap usage temporarily, you can use the swapoff -a command followed by swapon -a (but be careful as this could cause out-of-memory issues)

Combining free with Other Commands

The free command becomes even more powerful when combined with other Linux commands.

Piping with grep, awk, etc.

You can extract specific information from the free output using text processing tools:

free -m | grep "Mem:"

This command shows only the memory line from the output in megabytes.

To extract just the available memory value:

free -m | awk '/Mem:/ {print $7}'

This extracts and displays only the 7th field (available memory) from the Mem line.

Creating Simple Monitoring Scripts

Here’s a simple bash script that monitors memory usage and alerts when available memory falls below a threshold:

#!/bin/bash
THRESHOLD=500  # Alert when available memory is below 500 MB
while true; do
  AVAILABLE=$(free -m | awk '/Mem:/ {print $7}')
  if [ $AVAILABLE -lt $THRESHOLD ]; then
    echo "WARNING: Available memory ($AVAILABLE MB) is below threshold ($THRESHOLD MB)"
  fi
  sleep 60
done

This script checks available memory every minute and prints a warning when it falls below the specified threshold. You can extend it to send email alerts or take corrective actions automatically.

Best Practices and Tips

To get the most out of the free command, follow these best practices:

  1. Use human-readable format (-h) for easier interpretation of results
  2. Combine with other monitoring tools for a complete picture of system health
  3. Remember that high buffer/cache usage is usually beneficial for performance
  4. Monitor trends over time rather than focusing on a single snapshot
  5. Create automated monitoring scripts for critical systems to detect memory issues early
  6. When interpreting results, focus on the “available” column rather than just “free” memory
  7. Be aware that memory utilization changes quickly, so multiple samples provide better insights than a single reading

Common mistakes to avoid:

  1. Confusing “free” memory with “available” memory
  2. Panicking over low “free” memory when “available” memory is adequate
  3. Ignoring swap usage patterns
  4. Not considering the relationship between memory and other system resources like CPU and I/O

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button