5 Commands to Check Memory Usage in Linux

The Linux operating system offers a wide range of readily available tools to assist with system administration. With Linux, you have a wide range of tools at your disposal, from basic file and directory commands to advanced security features. There’s virtually no limit to what you can accomplish. Even though regular desktop users may not need to be familiar with these tools at the command line, they are essential for Linux admins. Why? At some point, you’ll need to work with a Linux server that doesn’t have a graphical user interface. Additionally, command-line tools frequently provide greater power and flexibility compared to their graphical user interface counterparts.

System administrators are responsible for maintaining the peak performance of a Linux system at all times. With a few basic terminal commands, you can easily access all the necessary information and keep track of memory statistics.

Understanding memory usage is a valuable skill to have in case a specific application becomes problematic and starts using up excessive system memory. When that occurs, it’s useful to be aware of the range of tools at your disposal for troubleshooting. Perhaps you require data on a Linux swap partition or in-depth details about your installed RAM? There are also commands available for that. Now, we’ll explore different Linux command-line tools that can assist in monitoring system memory usage. These tools are quite user-friendly, and in this article, we’ll demonstrate five distinct methods to tackle the issue.

Requirements

  • Having access to a command line/terminal is essential.
  • User with elevated privileges.

If you are new to memory management, we highly recommend checking out our comprehensive guide to memory management in operating systems. This guide provides an overview of fundamental memory management concepts and terminology necessary for comprehending its contents.

How to Monitor Memory Usage in Linux using the Command Line

Checking Linux memory usage via the command line is a very effective method and often the sole way to monitor memory usage on remote headless servers.

Here are some examples you can use to check memory usage via the command line interface.

Using the cat command

Open the /proc/meminfo file in your terminal using the cat command.

cat /proc/meminfo

/proc/meminfo provides information about the available and used memory in the system. It provides up-to-date data on the system’s memory usage, including buffers and shared memory utilized by the kernel.

Here is an example of the /proc/meminfo file in Ubuntu 22.04:

The values in the /proc/meminfo file are expressed in kibibytes.

Command free

Monitoring resource usage is done using the free command. It provides a comprehensive overview of the usage of RAM and swap space, including details on total, used, free, shared, buff/cache, and available memory.

Enter the command “free” in your terminal, without any additional options, to view detailed information about memory and swap usage, measured in kibibytes.

free

Let me break down the meaning of each column for you:

ColumnDescription
totalTotal installed memory.
usedMemory currently in use (excluding buffers and cache).
freeUnused memory.
sharedMemory used by tmpfs and shared between processes.
buff/cacheThe sum of buffer and cache memory, which are used by the operating system to speed up processes.
availableAn estimation of how much memory is available for starting new applications, without swapping.

Free provides data in a more user-friendly format compared to the /proc/meminfo file. The available value is crucial as it indicates the amount of memory that is still free for running new applications.

Users can customize the output of the free command by taking advantage of its various options.

OptionResult
-bOutput in bytes.
-kOutput in kibibytes.
-mOutput in mebibytes.
-gOutput in gibibytes.
-lDetailed low and high memory statistics.
-oOld format (no -/+buffers/cache line).
-tTotal for RAM + swap.
-sUpdate every [delay] seconds.
-cUpdate [count] times.

Try these choices to customize the memory usage output according to your requirements.

Using the vmstat command

The vmstat command provides detailed information on virtual memory statistics. Enter the command “vmstat” to obtain a comprehensive overview of the system’s virtual memory statistics, encompassing processes, memory usage, paging, block IO, traps, and CPU activity.

vmstat

Here is a list that can help you interpret the virtual memory statistics provided by vmstat.

Processes

r – The number of processes waiting for run time is represented by “r”.

b – Count of processes in uninterruptible sleep state.

Recall

Amount of virtual memory used: swpd.

free – These are the details about memory usage: the amount of idle memory buff – and the amount of memory used as buffers.

The cache is the memory used for caching purposes.

Exchange

si -Memory is swapped in from the disk at a certain rate.

so -Memory has been swapped to disk (/s).

Input/output (IO)

bi – Blocks received from a block device are measured in blocks per second.

bo -Blocks sent to a block device are measured in blocks per second.

System

in – Number of interrupts per second, including the clock

cs – The rate at which context switches occur per second.

Central Processing Unit

These values indicate the proportion of CPU time consumed.

us – Time spent executing non-kernel code, including user time and nice time.

sy – Amount of time dedicated to executing kernel code (system time).

id – the duration of inactivity. Prior to Linux 2.5.41, this encompasses IO-wait time.

wa – The time spent waiting for input/output. Prior to Linux 2.5.41, it was included in idle.

st – Time taken away from a virtual machine. Prior to Linux 2.6.11, the information was not available.

Profit from the data from the fields to pinpoint possible bottlenecks or areas that may benefit from optimization.

Using the top command

Understanding the top command is crucial for keeping track of CPU and memory usage for each process. To initiate the launch, simply input “top” in the terminal:

top

The system provides details on:

  • Ensuring uninterrupted system operation.
  • Typical workload.
  • Count of active tasks.
  • Count of users currently logged in.
  • Monitoring the CPU usage for each CPU or core.
  • Statistics on the usage of memory and swap by processes.

With continuous updates, you can easily track the activity and resources of the system in real time.

Not only does the top command provide crucial memory information, but it also offers an interactive interface that lets you sort processes, modify display settings, and handle operations without having to exit the tool.

Please press the ‘q’ key to exit the interface.

Brief manual for key commands and sorting options

Here’s a concise manual for key commands and sorting options in the `top` command:

Key Commands in `top`

  • h: Display help (provides information on key commands).
  • q: Quit the `top` interface.
  • Space: Refresh the display.
  • P: Sort by CPU usage (default).
  • M: Sort by memory usage.
  • N: Sort by process ID.
  • T: Sort by running time (cumulative).
  • K: Kill a process. You’ll be prompted to enter the PID of the process to kill.
  • r: Renice a process. You’ll be prompted to enter the PID and the new niceness value.
  • u: Display processes for a specific user. You’ll be prompted to enter the username.
  • f: Field management (add or remove columns in the display).
  • s: Change the delay between updates. You’ll be prompted to enter the new delay time in seconds.

Sorting Options

To sort processes by different criteria, you can press the following keys:

  • P: Sort by CPU usage (default).
  • M: Sort by memory usage.
  • N: Sort by process ID.
  • T: Sort by cumulative time.

Additional Commands

  • l: Toggle load average and uptime display.
  • t: Toggle task/cpu information.
  • m: Toggle memory information.
  • 1: Toggle between showing all CPUs and a summary of CPUs.

Display Customization

  • B: Bold the running tasks.
  • z: Color/monochrome toggle.
  • x: Highlight the sort column.
  • y: Toggle highlighting of running tasks.

Use these commands and options to effectively monitor and manage processes on your system using the `top` command.

Using the htop command

Similar to the top command, htop offers memory and CPU usage monitoring data, but it comes with various enhancements that create a more user-friendly environment and provide improved controls.

The output is color-coded and provides the ability to view full command lines for processes. In addition, htop offers the convenient feature of vertical and horizontal scrolling for process lists.

To launch htop, input the following command:

htop

The output is categorized into two primary sections:

  1. The first segment contains a summary with visual meters and text counters.
  1. The lower section organizes the detailed data for each process. Users have the ability to carry out actions on specific processes.

By implementing the shortcuts located at the bottom of the screen, users can effortlessly manipulate and customize processes without the need for manual command input.

If you come across a message saying “Command htop not found,” it’s possible that htop is not installed on your system. To install htop, you can use the command that is specific to your Linux distribution.

Linux DistributionCommand
Debian/Ubuntusudo apt install htop
RHEL 8+ and CentOS Streamsudo dnf install htop
Fedorasudo dnf install htop
Arch Linuxsudo pacman -S htop
openSUSEsudo zypper install htop

htop is a crucial tool for monitoring and managing system processes, thanks to its extensive interactive features.

sar Command

The sar tool is a handy utility for keeping an eye on system performance. It’s not just about memory usage. You have the option to use the -r option to monitor memory utilization statistics at regular intervals.

Here’s an example: input the command below to instruct sar to monitor memory usage statistics every second, for a total of five times:

sar -r 1 5

The metrics offer a comprehensive breakdown of your system’s memory utilization, showcasing various columns:

kbmemfree: kbmemfree indicates the quantity of available memory in kilobytes.

kbmemused: The value of kbmemused represents the amount of memory that is currently being employed, measured in kilobytes.

%memused: The percentage of memory that is currently being used.

The sar utility is included in the sysstat package, which may not come pre-installed on certain Linux distributions. Please use the correct command to install the sysstat package:

Linux DistributionCommand
Debian/Ubuntusudo apt install sysstat
RHEL 8+ and CentOS Streamsudo dnf install sysstat
Fedorasudo dnf install sysstat
Arch Linuxsudo pacman -S sysstat
openSUSEsudo zypper install sysstat

Just a heads up: the man command gives you a complete rundown of command functionalities. For a comprehensive understanding of the sar command, you can access the manual by entering “man sar” in your terminal. It will provide you with options, flags, examples, and detailed information.

/proc/meminfo

The /proc/meminfo file is a read-only resource that offers up-to-date information on the usage of system memory. While commands such as “free” and “cat” can be used to retrieve memory usage statistics, the information they provide may not be suitable for users seeking a concise summary of their system’s memory status.

If you’re interested in obtaining specific memory usage data, you can analyze the /proc/meminfo file using tools such as awk or grep. As an information security analyst, you can use the following command to fetch the total amount of free memory from the /proc/meminfo file:

grep MemFree /proc/meminfo

Important metrics to consider from the /proc/meminfo file are:

The MemTotal field represents the total amount of usable memory (RAM) in the system.

MemFree. Available memory. The quantity of unused physical memory within the system.

MemAvailable. Available memory. An approximation of the memory that can be implemented for launching fresh applications without the need for swapping.

Buffers. The physical memory utilized for file buffers.

Catched. The amount of physical RAM utilized as cache memory.

SwapTotal. Total swap memory. Can you please provide the total amount of physical swap memory?

SwapFree. Can you please provide the total amount of free swap memory? Active. Data is temporarily stored on the disk when it is evicted from RAM.

Inactive. The active usage of buffer/page cache memory can be determined by calculating the total amount in use. This memory was recently utilized and is typically not reallocated for other tasks.

Inactive. Not currently active. The current status of available buffer/page cache memory. This memory has not been recently utilized and can be freed up for other tasks.

Dirty. Data patiently awaiting to be written back to the disk.

Shmem. The total amount of shared memory being used includes memory shared between multiple processes, such as RAM disks, SYS-V-IPC, and BSD-like SHMEM.

SReclaimable: A portion of the Slab cache that can be recovered if needed, like other caches.

AnonPages: Anonymous pages are pages that are not backed by files and are instead mapped into userspace page tables.

CommitLimit. This is the total amount of memory currently available to be allocated to the system, determined by the overcommit ratio. Strict adherence to this limit is only possible when enabling strict overcommit accounting (mode 2 in vm.overcommit_memory).

Committed_AS: Committed_AS represents the current amount of memory allocated on the system. Committed memory encompasses the total memory allocated by processes, regardless of whether it has been utilized or not.

There are several other values in the /proc/meminfo file that could be useful for monitoring and troubleshooting system issues. Utilize tools such as grep or awk to narrow down your search to specific metrics.

How to Monitor Memory Usage in Linux Using a Graphical User Interface

It is less common to use a graphical interface for server administration in production environments. However, visual representations can greatly enhance the clarity and comprehension of certain data sets, such as memory usage in development and testing environments.

If you’re using a Linux system with a graphical desktop, accessing the System Monitor app will allow you to easily view memory consumption.

1. Go to Show Applications.

2. Open System Monitor by searching for it in the search bar and launching the application.

3. Click on the Resources tab.

The application provides a real-time graphical overview of your memory consumption, along with historical data.

In conclusion

In the practical world of Linux system administration, understanding and monitoring memory usage is crucial. Leveraging tools like `cat`, `free`, `vmstat`, `top`, `htop`, and `sar` offers a comprehensive view into the system’s memory landscape, enabling administrators to preempt performance bottlenecks and optimize resource allocation effectively. Each command provides unique insights, from real-time process monitoring to detailed virtual memory statistics, equipping tech professionals with the knowledge to maintain system health and ensure efficiency. As Linux continues to evolve, mastery of these tools isn’t just about keeping the lights on; it’s about driving performance in an increasingly data-intensive world.

After reading this article, you have gained the knowledge to effectively monitor memory usage on a Linux system and accurately interpret the provided information.

If your system often handles memory-intensive tasks, it’s important to understand how to utilize swap memory effectively. This will not only improve stability but also provide extra virtual memory space.

FAQs

The main commands are `cat`, `free`, `vmstat`, `top`, `htop`, and `sar`. Each provides different insights into memory usage, from detailed system statistics to real-time process monitoring.

The `cat` command can be used to display the contents of `/proc/meminfo`, which includes detailed information about system memory usage such as total, free, and used memory.

The `free` command provides a snapshot of the total, used, and free memory in the system along with buffer and cache usage. It is an essential tool for quickly assessing memory resources.

Yes, the `top` and `htop` commands allow you to monitor real-time memory and CPU usage for each process. `htop` provides an enhanced, user-friendly interface with additional features like vertical and horizontal scrolling.

`vmstat` reports information about processes, memory, paging, block IO, traps, and CPU activity, offering a comprehensive view of system performance.

The `sar` command is used to collect, report, and save system activity information, providing detailed reports on memory usage over time, which is vital for trend analysis and long-term system monitoring.

Command-line tools generally offer more detailed, extensive, and customizable information about memory usage. They are also accessible on remote or headless servers where a GUI is not available.

Access to a command line/terminal and elevated privileges (typically root access) are required to utilize these commands fully, especially for viewing detailed system statistics or making changes.