Website Vidya
Linux & ServersStep-by-Step Guide

top Command in Linux: Monitor CPU, Memory, and Processes in Real Time

Learn top command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
11 min read
PDF Cheat Sheet
top Command in Linux: Monitor CPU, Memory, and Processes in Real Time
AI Executive SummaryWebsiteVidya AI

11 min read

Learn top command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What top Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

The top command in linux is the universal real-time system monitor pre-installed on virtually every Linux server, virtual machine, and enterprise appliance. Even when third-party tools like htop or btop are not installed on a locked-down production host, top (part of procps-ng) is always present and ready for immediate incident triage.

The top interface is divided into two sections: a 5-line Summary Area at the top of the screen (reporting uptime, load averages, task state totals, eight granular CPU time percentages, physical RAM, and swap usage) and a scrollable Task Area below it that ranks active processes by resource consumption every 3.0 seconds by default.

Learning how to read the eight CPU state metrics in the summary header—especially wa (I/O wait), sy (kernel system time), si (software interrupts), and st (hypervisor steal time)—and mastering interactive single-key shortcuts turns top into a surgical diagnostic console.

Advertisement
top Command in Linux: Monitor CPU, Memory, and Processes in Real Time — syntax, flags, and practical terminal workflow diagram
top Command in Linux: Monitor CPU, Memory, and Processes in Real Time — command syntax, key options, and production workflow reference.

What top Does and When to Use It

On each refresh cycle, top samples global CPU tick counters from /proc/stat, memory statistics from /proc/meminfo, load averages from /proc/loadavg, and per-process delta jiffies across /proc/[0-9]*/stat. Unlike ps, which reports lifetime average CPU usage since process start, top computes the exact delta of CPU ticks consumed by each task between the previous screen refresh and the current refresh divided by the elapsed interval.

Understanding the eight fields on the %Cpu(s): line is vital for root-cause analysis: us (user-space application code), sy (kernel-space system calls), ni (niced user processes), id (idle time), wa (idle time while waiting on block disk/NFS I/O), hi (hardware IRQ servicing), si (software IRQ / network packet processing), and st (steal time—CPU cycles your virtual machine wanted to run but the cloud hypervisor allocated to a noisy neighbor).

Under the hood, top gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -d, -b, -n, -u turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The top utility is packaged in procps across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether top is installed and inspect which binary path and version your shell resolves:

type -a top
top --version 2>/dev/null || man -f top

# Illustrative output (reviewed against documentation)
top is /usr/bin/top
top (procps)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y procps

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y procps-ng

# Arch Linux
sudo pacman -S --noconfirm procps-ng

# Alpine Linux
sudo apk add --no-cache procps-ng

Command Syntax, Arguments, and Exit Status Codes

top [OPTIONS]

You can launch top interactively with startup flags that pre-filter or customize the view—such as top -d 1 (refresh every 1 second), top -u postgres (show only processes owned by user postgres), top -p 1104,29410 (monitor specific PIDs only), or top -o +%MEM (start sorted by memory consumption).

For automated scripts and cron jobs, top provides Batch Mode via -b combined with an iteration count -n N. Because the first iteration of top -b -n 1 includes boot-time baseline CPU counters, running two iterations with a 1-second delay (top -b -n 2 -d 1) yields the most accurate instantaneous CPU snapshot in log files.

  • 0 — Successful execution with no runtime or permission errors.
  • 1 — Operational failure, unmatched condition, or permission restriction.
  • 2 — Invalid command-line option or malformed syntax.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-d-d SECONDSSets the screen refresh delay interval in seconds (supports decimals such as -d 0.5 or -d 1.5; default is 3.0).
-b-b (Batch mode)Runs top in non-interactive batch mode without terminal escape codes, suitable for piping to files or awk.
-n-n ITERATIONSSpecifies the maximum number of refresh iterations top should produce before automatically exiting.
-u-u USER / UIDDisplays only processes owned by the specified effective username or numeric UID.
-p-p PID1,PID2,...Monitors only the specified comma-separated Process IDs (up to 20 PIDs).
-H-H (Threads mode)Instructs top to display individual kernel threads (LWP) rather than aggregating threads into their parent process.
-c-c (Command line)Toggles the COMMAND column between the short binary name and the full command path with arguments.
-o-o [+|-]FIELDSpecifies the initial column sort field on startup (e.g., -o +%MEM, -o +%CPU, or -o +TIME+).
-i-i (Idle toggle)Starts top with idle/sleeping tasks hidden so only actively running processes appear in the task table.

While running top interactively, single-letter hotkeys control the display without restarting the tool: press P (uppercase) to sort by %CPU, M to sort by %MEM, T to sort by cumulative TIME+, 1 to expand per-core CPU breakdown bars, c to show full command paths, E to cycle summary memory units between KiB, MiB, GiB, and TiB, k to send a signal (default 15) to a PID, r to renice a PID, and q to quit.

Advertisement

Note the difference between VIRT, RES, and SHR in the task table: VIRT is total virtual address space mapped (including shared libraries, mmap files, and unallocated memory), RES is actual physical RAM currently occupied by the process, and SHR is the portion of memory shared with other processes.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Capture a Non-Interactive Snapshot Using Batch Mode (-b -n 1)

Use -b (batch mode), -n 1 (one iteration), and -c (full command arguments) to record the top 12 processes to a terminal or incident log.

top -b -n 1 -c -w 120 | head -n 18

# Illustrative output (reviewed against documentation)
top - 19:52:10 up 42 days,  6:46,  2 users,  load average: 1.85, 1.42, 1.10
Tasks: 164 total,   2 running, 162 sleeping,   0 stopped,   0 zombie
%Cpu(s): 18.4 us,  3.2 sy,  0.0 ni, 76.1 id,  1.8 wa,  0.0 hi,  0.4 si,  0.1 st
MiB Mem :  15942.4 total,   3412.8 free,   5120.6 used,   7409.0 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.  10384.2 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
  18420 appuser   20   0  842100  61440  14200 R  98.2   0.4  12:44.18 python3 /opt/app/worker.py --queue=default
   4120 mysql     20   0 2418900 1.110g  38400 S  14.5   7.1 245:12.04 /usr/sbin/mysqld
  29410 www-data  20   0   56412  12440   6800 S   2.1   0.1   0:08.42 nginx: worker process
    984 postgres  20   0  218400  74216  68100 S   0.8   0.5   4:18.90 /usr/lib/postgresql/16/bin/postgres

Look at 'avail Mem' (10384.2 MiB) rather than 'free' (3412.8 MiB) when evaluating available RAM, because Linux uses free RAM for disk page caching (buff/cache) and reclaims it automatically when applications need memory.

2. Start top Pre-Sorted by Memory Usage (-o +%MEM)

Launch top directly sorted by highest memory percentage with full command lines enabled.

top -b -n 1 -o +%MEM -c | head -n 12

# Illustrative output (reviewed against documentation)
top - 19:54:02 up 42 days,  6:48,  2 users,  load average: 1.60, 1.40, 1.12
Tasks: 164 total,   1 running, 163 sleeping,   0 stopped,   0 zombie
%Cpu(s):  6.2 us,  1.4 sy,  0.0 ni, 91.8 id,  0.4 wa,  0.0 hi,  0.2 si,  0.0 st
MiB Mem :  15942.4 total,   3410.2 free,   5123.2 used,   7409.0 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.  10381.6 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
   4120 mysql     20   0 2418900 1.110g  38400 S   4.2   7.1 245:15.10 /usr/sbin/mysqld
   2190 redis     20   0  412800 324.1m   4200 S   1.1   2.0  88:04.22 /usr/bin/redis-server 127.0.0.1:6379
    984 postgres  20   0  218400  74216  68100 S   0.3   0.5   4:19.02 /usr/lib/postgresql/16/bin/postgres

Passing -o +%MEM on the command line is equivalent to pressing uppercase M interactively inside top.

3. Monitor Only Processes Owned by a Specific User (-u)

Isolate all processes running under a specific service account such as www-data or postgres.

top -b -n 1 -u www-data

# Illustrative output (reviewed against documentation)
top - 19:55:18 up 42 days,  6:49,  2 users,  load average: 0.45, 0.90, 0.98
Tasks: 164 total,   1 running, 163 sleeping,   0 stopped,   0 zombie
%Cpu(s):  2.1 us,  0.5 sy,  0.0 ni, 97.2 id,  0.1 wa,  0.0 hi,  0.1 si,  0.0 st
MiB Mem :  15942.4 total,   3470.0 free,   5063.4 used,   7409.0 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.  10441.4 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
  29410 www-data  20   0   56412  12440   6800 S   1.3   0.1   0:09.12 nginx
  29411 www-data  20   0   56412  12180   6600 S   0.7   0.1   0:07.88 nginx
  29450 www-data  20   0  214800  41200  28900 S   0.0   0.3   0:02.14 php-fpm8.3

You can also filter by user dynamically while inside interactive top by pressing u and typing the username.

4. Track Specific Process IDs with Sub-Second Refresh (-p and -d)

Use -p alongside pidof -d, to watch only the master and worker PIDs of a single daemon at a 1-second interval.

top -d 1 -n 1 -b -p "$(pidof -d ',' nginx)"

# Illustrative output (reviewed against documentation)
PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
   1104 root      20   0   55840   8920   5100 S   0.0   0.1   0:00.14 nginx
  29410 www-data  20   0   56412  12440   6800 S   1.0   0.1   0:09.40 nginx
  29411 www-data  20   0   56412  12180   6600 S   0.0   0.1   0:07.92 nginx

Combining pidof -d ',' with top -p focuses the entire task display on a single service's PIDs.

5. Inspect Individual Threads Inside a Process (-H -p)

When a multi-threaded Java, Go, or MySQL process spikes CPU usage, combine -H (threads mode) and -p <PID> to identify the exact thread ID (PID column in -H mode) burning CPU.

top -H -b -n 1 -p 4120 | head -n 12

# Illustrative output (reviewed against documentation)
Threads:  38 total,   1 running,  37 sleeping,   0 stopped,   0 zombie
%Cpu(s):  8.4 us,  1.2 sy,  0.0 ni, 89.8 id,  0.4 wa,  0.0 hi,  0.2 si,  0.0 st
MiB Mem :  15942.4 total,   3410.2 free,   5123.2 used,   7409.0 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.  10381.6 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S %CPU  %MEM     TIME+ COMMAND
   4145 mysql     20   0 2418900 1.110g  38400 R 32.4   7.1  42:18.90 ib_io_wr-1
   4146 mysql     20   0 2418900 1.110g  38400 S  6.2   7.1  18:04.11 connection
   4120 mysql     20   0 2418900 1.110g  38400 S  0.0   7.1   0:14.22 mysqld

In -H mode, the Tasks line changes to Threads, and the COMMAND column displays the individual kernel thread name (such as ib_io_wr-1).

6. Show Only Active (Non-Idle) Processes (-i)

Filter out hundreds of sleeping background daemons by passing -i (or pressing i interactively) so only tasks consuming CPU in the current interval are shown.

top -b -n 1 -i

# Illustrative output (reviewed against documentation)
PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
  18420 appuser   20   0  842100  61440  14200 R  96.4   0.4  13:12.05 python3
  32410 admin     20   0   11840   4120   3200 R   1.2   0.0   0:00.02 top

Hiding idle tasks keeps the screen uncluttered on servers running thousands of dormant worker processes.

Real-World Workflows, Pipelines, and Shell Automation

High-Precision CPU Spike Recorder Using Two-Iteration Batch Mode

Because the first iteration of top -b -n 1 reflects averages since boot, run 2 iterations spaced 1 second apart (top -b -n 2 -d 1) and extract only the second frame for accurate real-time alerting.

#!/usr/bin/env bash
set -euo pipefail

# Capture 2 iterations 1 second apart and print only the 2nd iteration's top 10 tasks
top -b -n 2 -d 1 -c -w 160 | awk '
  /^top - / { frame++ }
  frame == 2 { print }
' | head -n 17

# Illustrative output (reviewed against documentation)
top - 19:58:04 up 42 days,  6:52,  2 users,  load average: 1.52, 1.38, 1.12
Tasks: 164 total,   2 running, 162 sleeping,   0 stopped,   0 zombie
%Cpu(s): 16.2 us,  2.1 sy,  0.0 ni, 81.1 id,  0.4 wa,  0.0 hi,  0.2 si,  0.0 st
MiB Mem :  15942.4 total,   3410.0 free,   5123.4 used,   7409.0 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.  10381.4 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
  18420 appuser   20   0  842100  61440  14200 R  99.0   0.4  13:45.10 python3 /opt/app/worker.py --queue=default

Discarding frame 1 and keeping frame 2 ensures that %Cpu(s) and per-process %CPU measure the exact 1-second live window rather than historical boot averages.

Pinpoint Java/JVM High-CPU Thread and Match It to jstack Hex NID

Use top -H -p <JAVA_PID> to find the highest-CPU native thread ID, convert it to hexadecimal, and match it in a thread dump.

JAVA_PID=$(pgrep -o java || echo 4120)
TOP_TID=$(top -H -b -n 1 -p "$JAVA_PID" | awk 'NR==8 {print $1}')
HEX_TID=$(printf "0x%x" "$TOP_TID")
echo "Java PID: $JAVA_PID | Hot Thread LWP: $TOP_TID (Hex nid=$HEX_TID)"

# Illustrative output (reviewed against documentation)
Java PID: 4120 | Hot Thread LWP: 4145 (Hex nid=0x1031)

JVM thread dumps (jstack <PID>) print native Linux thread IDs in hexadecimal as nid=0x1031; converting top -H's decimal PID to hex maps the CPU spike directly to the offending Java stack trace.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding top inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

top supports a ”Secure Mode” (enabled via the -s flag or system-wide via /etc/toprc), which disables the interactive k (kill), r (renice), and delay-interval modification commands so unprivileged operators monitoring a shared screen cannot disrupt tasks.

If you customize your interactive layout (such as enabling per-core CPU bars with 1, full command paths with c, and color highlighting with z), pressing uppercase W writes your layout preferences to ~/.config/procps/toprc.

GNU/Linux, BSD, and BusyBox Implementation Differences

While every Unix-like OS includes a top utility, command-line flags and interactive hotkeys differ significantly between Linux (procps-ng), FreeBSD, and macOS.

For example, batch mode on Linux is top -b -n 1, whereas on macOS it is top -l 1 and on FreeBSD it is top -b 20. On Alpine Linux, BusyBox top supports -b -n 1 -d SEC but does not support -u or -p unless procps-ng is installed.

Troubleshooting Common Errors and Diagnostics

A single process shows %CPU greater than 100% (e.g., 380.0%)

Root Cause: By default, top operates in 'Irix mode' where 100% equals one full logical CPU core. A multi-threaded process utilizing 4 cores simultaneously will report up to 400% CPU.

Resolution: Press uppercase 'I' inside interactive top to toggle between Irix mode (per-core percentage) and Solaris mode (where total CPU across all cores sums to 100%).

# Press Shift+I inside interactive top to toggle Solaris mode

Long command lines are truncated in top -b batch output

Root Cause: top defaults to the terminal width (or 80 columns when redirected to a file) unless an explicit width override is passed.

Resolution: Pass -c along with -w 512 (maximum width in procps-ng) when capturing batch snapshots.

top -b -n 1 -c -w 512

'free' memory in top looks critically low (e.g., 200 MiB on a 32 GiB server)

Root Cause: The Linux kernel aggressively uses idle physical RAM for filesystem page caches and buffers ('buff/cache' in top). This memory is immediately reclaimed when applications call malloc().

Resolution: Always read the 'avail Mem' figure on the MiB Swap line rather than 'free' on the MiB Mem line to see true available memory.

free -h

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
While top is running, press uppercase M (Shift+M) to sort by resident memory percentage (%MEM), uppercase P (Shift+P) to sort by CPU usage (%CPU), or uppercase T (Shift+T) to sort by cumulative CPU time (TIME+).
wa (I/O wait) is the percentage of time the CPU spent idle waiting for local disk or network storage operations to complete. st (steal time) is the percentage of time a virtual CPU waited for the physical hypervisor to allocate CPU cycles on a shared cloud host.
VIRT is the total virtual memory address space mapped by the process (including swap, shared libraries, and unallocated reservations). RES (Resident Set Size) is the actual physical RAM currently used by the process. SHR is the subset of memory shared with other processes.
Press the number 1 key while top is running to expand the single %Cpu(s) summary row into individual utilization bars for every logical CPU core (%Cpu0, %Cpu1, etc.).
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout