Bash top Command – Complete Guide to Displaying Linux Tasks

Introduction to top

The top command is one of the most powerful and commonly used system monitoring tools in Linux/Unix systems. It provides a dynamic, real-time view of running processes, system resource usage, and overall system performance. Understanding top is essential for system administrators, developers, and anyone who needs to monitor and troubleshoot system performance.

What top Shows

  • System summary: Uptime, load average, tasks, CPU usage, memory usage
  • Process list: Running processes with their resource consumption
  • Real-time updates: Continuously updated display
  • Interactive commands: Sort, filter, and manage processes

Basic Syntax

top
top -options
top -p PID1,PID2  # Monitor specific PIDs

1. Basic Usage

Starting top

# Start top with default settings
top
# Start top in batch mode (for scripting)
top -b -n 1
# Start top with specific delay
top -d 5  # Update every 5 seconds
# Start top monitoring specific PIDs
top -p 1234,5678
# Start top for specific user
top -u username

Default top Display

When you run top, you'll see something like:

top - 10:30:15 up 3 days,  2:15,  3 users,  load average: 0.15, 0.10, 0.08
Tasks: 187 total,   1 running, 186 sleeping,   0 stopped,   0 zombie
%Cpu(s):  5.2 us,  1.3 sy,  0.0 ni, 93.2 id,  0.2 wa,  0.0 hi,  0.1 si,  0.0 st
MiB Mem :  15892.3 total,   2345.6 free,   6789.2 used,   6757.5 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.   7890.1 avail Mem 
PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
1234 root      20   0  345678  12345   9876 S   5.2   0.8   0:12.34 systemd
5678 user      20   0  234567  23456  12345 R   4.5   1.5   0:45.67 firefox

2. Understanding the Display

System Summary Line

top - 10:30:15 up 3 days,  2:15,  3 users,  load average: 0.15, 0.10, 0.08
#      |          |            |        |                    |
#      |          |            |        |                    +-- Load average (1,5,15 min)
#      |          |            |        +-- Number of users
#      |          |            +-- System uptime
#      |          +-- Current time
#      +-- Program name and current time

Tasks Line

Tasks: 187 total,   1 running, 186 sleeping,   0 stopped,   0 zombie
#       |            |           |              |            |
#       |            |           |              |            +-- Zombie processes
#       |            |           |              +-- Stopped processes
#       |            |           +-- Sleeping processes
#       |            +-- Running processes
#       +-- Total processes

CPU Usage Line

%Cpu(s):  5.2 us,  1.3 sy,  0.0 ni, 93.2 id,  0.2 wa,  0.0 hi,  0.1 si,  0.0 st
#          |       |       |       |       |       |       |       |
#          |       |       |       |       |       |       |       +-- Steal time (virtualized)
#          |       |       |       |       |       |       +-- Software interrupt
#          |       |       |       |       |       +-- Hardware interrupt
#          |       |       |       |       +-- I/O wait
#          |       |       |       +-- Idle
#          |       |       +-- Nice (low priority)
#          |       +-- System (kernel)
#          +-- User

Memory Lines

MiB Mem :  15892.3 total,   2345.6 free,   6789.2 used,   6757.5 buff/cache
#           |                |              |              |
#           |                |              |              +-- Buffer/cache memory
#           |                |              +-- Used memory
#           |                +-- Free memory
#           +-- Total physical memory
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.   7890.1 avail Mem
#           |                |              |              |
#           |                |              |              +-- Available memory
#           |                |              +-- Used swap
#           |                +-- Free swap
#           +-- Total swap space

Process List Columns

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
#  |   |        |   |      |      |      |   |    |     |       |      |
#  |   |        |   |      |      |      |   |    |     |       |      +-- Command name
#  |   |        |   |      |      |      |   |    |     |       +-- CPU time (hundredths)
#  |   |        |   |      |      |      |   |    |     +-- Memory usage
#  |   |        |   |      |      |      |   |    +-- CPU usage
#  |   |        |   |      |      |      |   +-- Process status
#  |   |        |   |      |      |      +-- Shared memory
#  |   |        |   |      |      +-- Resident memory
#  |   |        |   |      +-- Virtual memory
#  |   |        |   +-- Nice value
#  |   |        +-- Priority
#  |   +-- User owner
#  +-- Process ID

Process Status Codes:

  • R - Running
  • S - Sleeping (interruptible)
  • D - Uninterruptible sleep (usually I/O)
  • T - Stopped (by job control signal)
  • Z - Zombie (terminated but not reaped by parent)

3. Interactive Commands

Global Commands

# h or ? - Help
Press 'h' or '?' to display help screen
# q - Quit
Press 'q' to exit top
# Space - Update immediately
Press Space to refresh display
# Enter - Refresh display
Press Enter to refresh

Sorting Commands

# Sort by CPU usage (default)
Press 'P' (capital P)
# Sort by Memory usage
Press 'M' (capital M)
# Sort by Time (running time)
Press 'T' (capital T)
# Sort by PID
Press 'N' (capital N)
# Sort by specific field
Press 'O' then select field letter
# Reverse sort
Press 'R' to toggle reverse sort

Process Management

# Kill a process
Press 'k' then enter PID and signal (default: 15 - TERM)
# Renice a process
Press 'r' then enter PID and nice value (-20 to 19)
# Change process display
Press 'u' then enter username to show only that user's processes
Press 'U' then enter username to show processes containing that user
# Show/hide threads
Press 'H' to toggle thread view
# Show absolute paths
Press 'c' to toggle command line/path display

Display Control

# Change update delay
Press 'd' or 's' then enter seconds
# Toggle display of idle processes
Press 'i' to toggle idle processes
# Toggle display of cumulative time
Press 'S' to toggle cumulative time mode
# Change number of processes shown
Press 'n' then enter number
# Highlight running processes
Press 'y' or 'z' for color/monochrome
Press 'b' for bold/reverse

Field Management

# Manage displayed fields
Press 'f' to enter field management screen
# In field management:
# - Use up/down arrows to navigate
# - Press 'd' or Space to toggle field display
# - Press 's' to set sort field
# - Press 'q' to exit
# Available fields include:
PID     - Process ID
USER    - User owner
PR      - Priority
NI      - Nice value
VIRT    - Virtual memory
RES     - Resident memory
SHR     - Shared memory
S       - Process status
%CPU    - CPU usage
%MEM    - Memory usage
TIME+   - CPU time
COMMAND - Command name

4. Command-Line Options

Basic Options

# -d: Set delay between updates
top -d 5  # Update every 5 seconds
# -n: Number of iterations
top -n 3  # Run for 3 iterations then exit
# -b: Batch mode (for scripts)
top -b -n 1 > top_output.txt
# -p: Monitor specific PIDs
top -p 1234,5678,9012
# -u: Monitor specific user
top -u username
# -U: Monitor processes owned by user
top -U username

Advanced Options

# -H: Show individual threads
top -H
# -i: Hide idle processes
top -i
# -c: Show command line
top -c
# -w: Set output width (batch mode)
top -b -n 1 -w 512
# -1: Show individual CPU stats
top -1

Combining Options

# Monitor specific PIDs with 2-second updates
top -d 2 -p 1234,5678
# Batch mode for specific user
top -b -n 1 -u username > report.txt
# Show threads for specific PID
top -H -p 1234
# Customized display for monitoring
top -d 5 -i -c

5. Batch Mode and Scripting

Batch Mode Usage

# Single snapshot to file
top -b -n 1 > snapshot.txt
# Multiple snapshots
top -b -n 5 -d 2 > multiple.txt
# Monitor and append to log
while true; do
top -b -n 1 >> monitor.log
sleep 10
done

Script Examples

System Monitor Script:

#!/bin/bash
# monitor.sh - System monitoring with top
LOG_DIR="/var/log/system_monitor"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOG_FILE="$LOG_DIR/monitor_$TIMESTAMP.log"
# Create log directory if it doesn't exist
mkdir -p "$LOG_DIR"
# Function to log system stats
log_stats() {
echo "=== System Monitor Report $(date) ===" >> "$LOG_FILE"
# CPU and memory summary
echo "--- System Summary ---" >> "$LOG_FILE"
top -b -n 1 | head -5 >> "$LOG_FILE"
# Top 10 CPU processes
echo "--- Top 10 CPU Processes ---" >> "$LOG_FILE"
top -b -n 1 | awk 'NR>7 && NR<18 {print $0}' | sort -k9rn >> "$LOG_FILE"
# Top 10 Memory processes
echo "--- Top 10 Memory Processes ---" >> "$LOG_FILE"
top -b -n 1 | awk 'NR>7 && NR<18 {print $0}' | sort -k10rn >> "$LOG_FILE"
echo "----------------------------------------" >> "$LOG_FILE"
}
# Main monitoring loop
echo "Starting system monitor. Logs saved to $LOG_FILE"
echo "Press Ctrl+C to stop"
while true; do
log_stats
sleep 60  # Log every minute
done

Alert Script:

#!/bin/bash
# alert.sh - Alert on high resource usage
CPU_THRESHOLD=80
MEM_THRESHOLD=90
check_resources() {
# Get CPU usage (excluding idle)
CPU_USAGE=$(top -b -n 1 | grep "%Cpu" | awk '{print $2}' | cut -d'%' -f1)
# Get memory usage
MEM_USAGE=$(top -b -n 1 | grep "MiB Mem" | awk '{print $8}' | cut -d'.' -f1)
if (( $(echo "$CPU_USAGE > $CPU_THRESHOLD" | bc -l) )); then
echo "WARNING: High CPU usage: $CPU_USAGE%"
echo "Top CPU processes:" 
top -b -n 1 | awk 'NR>7 && NR<12 {print $0}'
fi
if (( MEM_USAGE > MEM_THRESHOLD )); then
echo "WARNING: High memory usage: $MEM_USAGE%"
fi
}
check_resources

6. Customizing top Display

Configuration File

top can be configured using ~/.toprc or /etc/toprc

# Create configuration by running top and pressing 'W'
# This saves current settings to ~/.toprc
# Example .toprc content
RCfile for "top with windows"       # Increment, plus a name
Id:i, Mode:0, Display:0, FirstWin:1
def fieldscur=AEHIOQTWKNMbcdefgjlmpqrstuvxyz
winflags=131380, sortindx=9, maxtasks=0
summclr=6, msgsclr=6, headclr=7, taskclr=6

Customizing Fields

# Interactive field customization
# 1. Press 'f' to enter field management
# 2. Use arrow keys to navigate
# 3. Press 'd' or Space to toggle fields
# 4. Press 's' to set sort field
# 5. Press 'q' to exit
# Common field toggles:
# * PID       - Always show
# * USER      - Show user
# * %CPU      - CPU usage
# * %MEM      - Memory usage
# * TIME+     - CPU time
# * COMMAND   - Command name

Color Configuration

# Toggle color/monochrome
Press 'z' to toggle color
# Toggle bold
Press 'b' to toggle bold
# Custom colors in .toprc
# Example color settings:
headclr=7     # Header color
taskclr=6     # Task color
msgclr=6      # Message color

7. Practical Examples

Performance Monitoring

# Monitor specific application
top -p $(pgrep -d',' nginx)
# Find processes using most CPU
top -b -n 1 | awk 'NR>7 {print $0}' | sort -k9rn | head -10
# Find processes using most memory
top -b -n 1 | awk 'NR>7 {print $0}' | sort -k10rn | head -10
# Monitor real-time with highlighting
top -d 1 | grep --color=always -E ".*(firefox|chrome).*|$"

System Health Checks

# Check system load
top -b -n 1 | head -1 | awk '{print $10,$11,$12}'
# Check CPU distribution
top -b -n 1 | grep "%Cpu" | awk '{print "User:"$2" System:"$4" Idle:"$8}'
# Check memory usage percentage
top -b -n 1 | grep "MiB Mem" | awk '{printf "%.1f%%\n", ($8/$4)*100}'
# Count processes by state
top -b -n 1 | grep "Tasks:" | awk '{print "Running:"$4,"Sleeping:"$6,"Zombie:"$10}'

Process Analysis

# Show process tree with top (use H for threads)
top -H
# Monitor process and its children
top -p $(pstree -p PID | grep -oP '\d+' | tr '\n' ',' | sed 's/,$//')
# Show processes with specific name
top -p $(pgrep -f "python" | tr '\n' ',' | sed 's/,$//')

8. Alternative Tools and Comparisons

top vs Other Monitoring Tools

ToolDescriptionUse Case
topReal-time process viewerGeneral system monitoring
htopInteractive process viewer (colorful, mouse support)User-friendly monitoring
atopAdvanced system monitorDetailed performance analysis
glancesCross-platform monitoringComprehensive overview
vmstatVirtual memory statisticsMemory and I/O analysis
iostatI/O statisticsDisk performance
mpstatCPU statisticsMulti-processor analysis
sarSystem activity reporterHistorical data collection

Using htop (Enhanced Alternative)

# Install htop
sudo apt install htop  # Debian/Ubuntu
sudo yum install htop  # RHEL/CentOS
# Run htop
htop
# htop features:
# - Color-coded output
# - Mouse support
# - Tree view
# - Vertical and horizontal scrolling
# - Easier process management

Using atop for Historical Data

# Install atop
sudo apt install atop
# Start recording
sudo systemctl start atop
# View historical data
atop -r /var/log/atop/atop_$(date +%Y%m%d)
# Playback specific time
atop -r /var/log/atop/atop_20240310 -b 10:00 -e 11:00

9. Performance Considerations

Impact of top on System

# top itself consumes resources
# Monitor top's own resource usage
top -p $(pgrep top)
# For minimal impact, use batch mode with low frequency
top -b -d 10 -n 1 > /dev/null

Optimization Tips

# Increase update interval for lower overhead
top -d 5  # Update every 5 seconds instead of default 3
# Use specific PID monitoring
top -p 1234  # Monitor only specific process
# Use batch mode for scripting (lower overhead)
top -b -n 1 > snapshot.txt
# Limit displayed processes
top -n 50  # Show only 50 processes

10. Advanced Features

Process Filtering

# Show only processes of specific user
Press 'u' then enter username
# Show only specific processes (using watch)
watch -n 1 'top -b -n 1 | grep -E "(PID|firefox|chrome)"'
# Show processes with specific state
top -b -n 1 | grep " R "  # Running processes
top -b -n 1 | grep " S "  # Sleeping processes
top -b -n 1 | grep " Z "  # Zombie processes

Tree View

# Show process tree (with H for threads)
top -H
# Alternative: use pstree with top
pstree -p | grep -B3 -A3 "process_name"

Logging and Historical Data

# Continuous logging
while true; do
echo "=== $(date) ===" >> top_history.log
top -b -n 1 | head -20 >> top_history.log
sleep 60
done
# Rotating logs
logrotate -f /etc/logrotate.d/top_monitor

11. Troubleshooting

Common Issues

# Issue: top shows 100% CPU but process unknown
# Solution: Check threads
top -H
# Issue: Can't see all processes
# Solution: Check if running as root
sudo top
# Issue: Display corrupted
# Solution: Reset terminal
reset
stty sane

Debugging High Resource Usage

# Find CPU spikes
top -b -d 1 | awk '$9 > 50 {print strftime("%Y-%m-%d %H:%M:%S"), $0}'
# Find memory leaks
top -b -d 60 -p $(pgrep -f "myapp") | \
awk '{print strftime("%Y-%m-%d %H:%M:%S"), $10}' >> memory_usage.log
# Monitor I/O wait
top -b -d 1 | grep "%Cpu" | awk '{print strftime("%H:%M:%S"), $8}'

12. Integration with Other Commands

Piping and Redirection

# Save top output
top -b -n 1 > top_snapshot.txt
# Email top output
top -b -n 1 | mail -s "System Snapshot" [email protected]
# Process top output with awk
top -b -n 1 | awk 'NR>7 {sum+=$9} END {print "Total CPU: "sum"%"}'
# Format top output
top -b -n 1 | column -t

Combining with System Commands

# Find process with highest CPU
top -b -n 1 | tail -n +8 | sort -k9rn | head -1
# Kill all processes above threshold
top -b -n 1 | awk '$9 > 90 {print $1}' | xargs kill -9
# Generate HTML report
{
echo "<html><body><h1>System Report</h1><pre>"
top -b -n 1
echo "</pre></body></html>"
} > report.html

13. Script Examples

Resource Monitor with Alerts

#!/bin/bash
# resource_monitor.sh - Monitor system resources with alerts
THRESHOLD_CPU=80
THRESHOLD_MEM=90
CHECK_INTERVAL=5
ALERT_EMAIL="[email protected]"
check_resources() {
local cpu_usage=$(top -b -n 1 | grep "%Cpu" | awk '{print $2}' | cut -d'%' -f1)
local mem_usage=$(top -b -n 1 | grep "MiB Mem" | awk '{printf "%.0f", ($8/$4)*100}')
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
if (( $(echo "$cpu_usage > $THRESHOLD_CPU" | bc -l) )); then
echo "ALERT: High CPU usage at $timestamp: $cpu_usage%"
top -b -n 1 | awk 'NR>7 && NR<12 {print $0}' | \
mail -s "High CPU Alert" "$ALERT_EMAIL"
fi
if (( mem_usage > THRESHOLD_MEM )); then
echo "ALERT: High memory usage at $timestamp: $mem_usage%"
top -b -n 1 | head -15 | \
mail -s "High Memory Alert" "$ALERT_EMAIL"
fi
}
echo "Starting resource monitor (Ctrl+C to stop)"
while true; do
check_resources
sleep $CHECK_INTERVAL
done

Performance Report Generator

#!/bin/bash
# perf_report.sh - Generate performance report
REPORT_DIR="/var/log/perf_reports"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
REPORT_FILE="$REPORT_DIR/report_$TIMESTAMP.txt"
mkdir -p "$REPORT_DIR"
{
echo "========================================="
echo "System Performance Report"
echo "Generated: $(date)"
echo "========================================="
echo
echo "System Uptime and Load:"
top -b -n 1 | head -1
echo
echo "CPU Usage Summary:"
top -b -n 1 | head -3 | tail -1
echo
echo "Memory Usage Summary:"
top -b -n 1 | head -4 | tail -2
echo
echo "Top 10 CPU-Consuming Processes:"
echo "-----------------------------------------"
printf "%-8s %-8s %-8s %-8s %-8s %s\n" "PID" "USER" "%CPU" "%MEM" "TIME" "COMMAND"
top -b -n 1 | tail -n +8 | sort -k9rn | head -10 | \
awk '{printf "%-8s %-8s %-8s %-8s %-8s %s\n", $1, $2, $9, $10, $11, $12}'
echo
echo "Top 10 Memory-Consuming Processes:"
echo "-----------------------------------------"
printf "%-8s %-8s %-8s %-8s %-8s %s\n" "PID" "USER" "%CPU" "%MEM" "TIME" "COMMAND"
top -b -n 1 | tail -n +8 | sort -k10rn | head -10 | \
awk '{printf "%-8s %-8s %-8s %-8s %-8s %s\n", $1, $2, $9, $10, $11, $12}'
echo
echo "Process Count by State:"
top -b -n 1 | grep "Tasks:" | \
awk '{print "  Running: " $4 "\n  Sleeping: " $6 "\n  Stopped: " $8 "\n  Zombie: " $10}'
echo
echo "========================================="
echo "End of Report"
echo "========================================="
} > "$REPORT_FILE"
echo "Report generated: $REPORT_FILE"

Interactive Process Manager

#!/bin/bash
# proc_manager.sh - Interactive process management
while true; do
clear
echo "=== Process Manager ==="
echo "1) Show top CPU processes"
echo "2) Show top Memory processes"
echo "3) Kill a process"
echo "4) Change process priority"
echo "5) Monitor specific user"
echo "6) Exit"
echo
read -p "Select option: " option
case $option in
1)
clear
echo "Top CPU Processes:"
top -b -n 1 | head -20
read -p "Press Enter to continue..."
;;
2)
clear
echo "Top Memory Processes:"
top -b -n 1 | head -20 | sort -k10rn
read -p "Press Enter to continue..."
;;
3)
clear
top -b -n 1 | head -20
read -p "Enter PID to kill: " pid
read -p "Enter signal (default 15): " signal
signal=${signal:-15}
kill -$signal $pid 2>/dev/null && \
echo "Process $pid killed" || \
echo "Failed to kill process $pid"
sleep 2
;;
4)
clear
top -b -n 1 | head -20
read -p "Enter PID to renice: " pid
read -p "Enter nice value (-20 to 19): " nice
renice $nice $pid 2>/dev/null && \
echo "Process $pid renice to $nice" || \
echo "Failed to renice process $pid"
sleep 2
;;
5)
clear
read -p "Enter username: " username
top -u "$username" 2>/dev/null
;;
6)
echo "Exiting..."
exit 0
;;
*)
echo "Invalid option"
sleep 1
;;
esac
done

14. Quick Reference Card

Interactive Commands Quick Reference

CommandAction
h or ?Help
qQuit
SpaceUpdate immediately
PSort by CPU
MSort by Memory
TSort by Time
NSort by PID
RReverse sort
kKill process
rRenice process
uFilter by user
UShow user processes
iToggle idle processes
cToggle command line
HToggle threads
fField management
d or sChange delay
WWrite configuration
zToggle color
bToggle bold
yHighlight running
xHighlight sort column

Command Line Options Quick Reference

OptionDescription
-d secondsUpdate delay
-n iterationsNumber of iterations
-bBatch mode
-p PID[,PID...]Monitor specific PIDs
-u usernameMonitor user
-U usernameMonitor user processes
-HShow threads
-iHide idle
-cShow command line
-w widthOutput width
-1Individual CPUs

Field Letters Reference

LetterFieldDescription
APIDProcess ID
BPPIDParent Process ID
CRUSERReal user name
DUIDUser ID
EUSERUser name
FGROUPGroup name
GTTYControlling terminal
HPRPriority
ININice value
JPLast used CPU
K%CPUCPU usage
LTIMECPU time
MTIME+CPU time (hundredths)
N%MEMMemory usage
OVIRTVirtual memory
PSWAPSwapped size
QRESResident memory
RCODECode size
SDATAData + stack
TSHRShared memory
UnFLTPage faults
VnDRTDirty pages
WSProcess status
XCOMMANDCommand name

Conclusion

The top command is an essential tool for system monitoring and process management:

Key Points Summary

  1. Real-time Monitoring: Dynamic view of system resources and processes
  2. Interactive Commands: Sort, filter, and manage processes on the fly
  3. System Summary: Uptime, load average, CPU, memory, swap information
  4. Process Information: Detailed view of each process's resource usage
  5. Batch Mode: For scripting and logging
  6. Customization: Configurable display, fields, and colors

Best Practices

  1. Regular Monitoring: Check top periodically to understand normal system behavior
  2. Use Batch Mode: For automated monitoring and logging
  3. Combine with Other Tools: Use alongside htop, atop, vmstat for comprehensive analysis
  4. Set Baselines: Know what's normal for your system
  5. Automate Alerts: Use scripts with top to detect issues early
  6. Understand Fields: Know what each column means for accurate interpretation

Quick Reference

Want to…Command/Action
Start toptop
Sort by CPUPress P
Sort by MemoryPress M
Kill processPress k
Change update delayPress d
Filter by userPress u
Save configurationPress W
Batch mode snapshottop -b -n 1
Monitor specific PIDtop -p 1234
Monitor usertop -u username

The top command's comprehensive real-time system view makes it indispensable for system administrators, developers, and anyone needing to understand and optimize system performance.

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper