# Advanced Guide to Using the top Command in Linux

- URL: https://karandeepsingh.ca/posts/mastering-top/
- Author: Karandeep Singh
- Published: 2024-03-26
- Updated: 2024-03-28
- Tags: bash, linux-monitoring
- Summary: The Linux top command is an essential tool for real-time system monitoring, providing a dynamic overview of running processes and their resource consumption. This guide digs deep into the functionalities of the top command, offering users of all skill levels, from novices to seasoned system administrators, a detailed look at how to utilize this tool effectively. Starting with the basics of launching and reading top, the guide progresses through intermediate techniques like sorting and filtering processes, and advances into complex uses such as batch mode operation and remote system monitoring. Practical examples in each section demonstrate how to apply these techniques in real-world scenarios, enhancing understanding and skill. Additionally, the guide addresses common questions through a thorough FAQ section, equipping users with the knowledge to troubleshoot common issues and optimize system performance. The conclusion ties everything together, suggesting further resources for expanding beyond top to other diagnostic tools, thereby providing a rounded approach to system management.

![Performance analytics graphs on a laptop screen for system monitoring](https://karandeepsingh.ca/images/posts/mastering-top.jpg)

## Introduction to the `top` Command

If you've ever wanted to peek behind the curtain to see what makes your Linux system tick, the `top` command is your front-row ticket. It's like having a dynamic, real-time x-ray of your computer's internals, from CPU load to memory usage.

### Overview and Purpose

The `top` command is a stalwart companion for anyone running a Linux system. It serves up a complete snapshot of what's happening on your machine at any given moment. `top` provides valuable data that helps you understand how your system's resources are being used.

### Importance in System Monitoring

Why is `top` so crucial? It's all about visibility. With `top`, you can immediately see which processes are being resource hogs, how your memory is being allocated, and much more. This visibility is essential, whether you're troubleshooting a slow system, managing server load, or just curious about what’s happening under the hood.

Understanding `top` is like learning to read the vital signs of your Linux system. It's the first step towards effective system management, and it enables you to make informed decisions about resource allocation and system performance optimization.

The following sections cover how to get started with `top`, including how to interpret its myriad details and tweak its many options to suit your needs. Practical examples throughout will help you become proficient with this tool, ensuring you can apply your knowledge immediately.

---

## Getting Started with the `top` Command

Navigating the `top` command doesn't have to be daunting. Let's break down the essentials, from launching the command to understanding what you're seeing on your screen.

### Basic Usage and Syntax

To start, open your terminal. Typing `top` and pressing Enter is like flipping the switch on a monitoring powerhouse. The screen that appears might look busy, but it's simply giving you a live overview of your system's activity.

**Command to launch `top`:**
```bash
top
```

This command refreshes every few seconds, providing an up-to-date snapshot of your system's state. You can exit anytime by pressing `q`.

### Reading the Output

When `top` loads up, you'll see several key pieces of information:

- **Tasks:** Shows the total number of processes, how many are running, sleeping, stopped, or zombie.
- **CPU(s):** Indicates how the CPU is being used. Look out for user processes, system processes, and idle time.
- **Mem:** Outlines how much memory is being used and how much is free.
- **Swap:** Provides information on swap usage, crucial when your memory is full.

Here's a quick guide to what the initial display sections mean:

```
top - 15:32:39 up  2:43,  1 user,  load average: 0.00, 0.01, 0.05
Tasks:  89 total,   2 running,  87 sleeping,   0 stopped,   0 zombie
%Cpu(s):  5.2 us,  2.8 sy,  0.0 ni, 91.0 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
MiB Mem :   3926.7 total,   142.0 free,   525.3 used,  3259.4 buff/cache
MiB Swap:   1024.0 total,   700.0 free,   324.0 used.  2556.0 avail Mem
```

### Practical Examples for Beginners

Let's practice using some simple but useful commands:

1. **Change the refresh interval:** By default, `top` updates every few seconds, but you can change this interval to 1 second by running:

```bash
top -d 1
```

2. **Sort by memory usage:** To see which processes are using the most memory, press `Shift + M` while `top` is running.

3. **Kill a process:** If you notice a process consuming too many resources, you can terminate it directly from `top`. Note the PID of the process, then press `k`, enter the PID, and hit Enter to kill it.

These basics will help you start monitoring your system effectively, giving you the power to observe and manage your system's health in real-time.

---

## Intermediate Uses of the `top` Command

As you become more comfortable with `top`, you can start tailoring its functionality to better meet your needs. This section explores how to filter and sort data, and how to customize the display to focus on the metrics that matter most to you.

### Filtering and Sorting Processes

**Sorting Processes:** By default, `top` sorts processes by CPU usage, which is useful for quickly identifying resource-intensive tasks. However, you might want to see processes sorted by other metrics like memory (RAM) usage.

- **To sort by memory usage:**
  Press `Shift + M` in `top`. This sorts the list by resident memory usage, making it easy to spot processes consuming the most RAM.

- **To sort by process ID (useful for tracking new processes):**
  Press `Shift + N` to reorder the display by PID.

**Filtering Processes by User:** If you're only interested in processes run by a specific user, `top` can be filtered accordingly.

- **To display only a specific user's processes, use:**
  ```bash
  top -u username
  ```
  Replace `username` with the actual user name to see only their processes.

### Customizing the Display

`top` is highly customizable, allowing you to choose which columns are displayed and how they are ordered.

- **Selecting fields to display:**
  Press `f` while running `top` to open the Fields Management screen. Use the arrow keys to navigate and select or deselect fields by pressing `d` or `Space`.

- **Saving custom settings:**
  Once you've set up `top` to display exactly what you need, you can save these settings so that `top` always opens with your configuration. Simply press `Shift + W` to write the current setup to your personal configuration file.

### Practical Examples for Intermediate Users

Let's apply what we've learned with some step-by-step examples:

1. **Monitoring specific users:**
   Suppose you want to monitor processes run by the user `alice`. You would start `top` like this:
   ```bash
   top -u alice
   ```
   This command helps you monitor if a particular user’s processes are affecting system performance.

2. **Customizing fields:**
   Maybe you're particularly interested in the number of threads each process is using. Here’s how to add that column:
   - Start `top` and press `f`.
   - Navigate to `nTH` (number of threads) and press `Space` to select it.
   - Press `Enter` to save and exit the field selection.

3. **Finding and killing high-memory processes:**
   - Open `top` and sort by memory usage by pressing `Shift + M`.
   - Identify a process consuming too much memory.
   - Note its PID, press `k`, enter the PID, type the signal (e.g., `15` for `TERM`), and press `Enter` to terminate it.

These intermediate techniques will enhance your ability to monitor and manage processes more effectively, offering more control over your system's resources.

---

## Advanced Techniques with the `top` Command

When you're ready to go beyond the basics and intermediate functionalities of `top`, several advanced techniques can significantly expand its utility. From automating monitoring tasks to keeping an eye on remote systems, these advanced tips will help you use the full power of `top`.

### Using `top` in Batch Mode

Batch mode in `top` is particularly useful for capturing snapshots of the system's state without the interactive interface, ideal for logging or automated monitoring scripts.

- **To run `top` in batch mode:**
  ```bash
  top -b -n 1 > top-output.txt
  ```
  This command runs `top` in batch mode (`-b`), takes one snapshot (`-n 1`), and redirects the output to a file called `top-output.txt`. You can review this file later or use it as part of a system monitoring setup.

### Remote System Monitoring

Monitoring remote Linux systems is crucial for managing multiple servers or working in a distributed environment. You can use `top` remotely by combining it with `ssh`.

- **To monitor a remote system using `top`:**
  ```bash
  ssh username@hostname top
  ```
  Replace `username` with your remote username and `hostname` with the address of the remote server. This command logs you into the remote server and starts `top`, allowing you to monitor that system as if you were logged in locally.

### Integrating `top` with Scripts

For system administrators, integrating `top` with scripts can automate routine monitoring tasks, alerting you when certain thresholds are reached.

- **Example script to monitor CPU load:**
  ```bash
  #!/bin/bash
  top -b -n 1 | grep "Cpu(s)" | awk '{print $2}' | while read output;
  do
    echo "Current CPU Load: $output%"
    if [ $(echo "$output > 75" | bc) -eq 1 ]; then
      echo "High CPU load detected" | mail -s "CPU Load Alert" admin@example.com
    fi
  done
  ```
  This script captures the CPU usage from `top`, checks if it exceeds 75%, and sends an email alert if it does.

### Practical Examples for Advanced Usage

1. **Automating system snapshots:**
   Use a cron job to run `top` in batch mode at regular intervals, storing outputs for later review:
   ```bash
   0 * * * * /usr/bin/top -b -n 1 -o %CPU > /var/log/top-hourly.txt
   ```
   This cron entry captures the system state sorted by CPU usage every hour and saves it to a log file.

2. **Remote troubleshooting:**
   If you're diagnosing issues on a remote server, use `ssh` with `top` to see real-time statistics without logging into the server's console:
   ```bash
   ssh admin@192.168.1.100 top -i
   ```
   This connects to the server at `192.168.1.100` and runs `top` with idle processes hidden, focusing on the active ones.

---

## Managing Process Priorities with `nice` and `chrt`

In Linux, every process runs with a priority level that helps the system determine how much CPU time it should allocate to each process. Managing these priority levels can significantly impact system performance, especially on systems with high load. Two tools that are essential for managing these priorities are `nice` and `chrt`.

### Understanding `nice` Values

The `nice` value of a process determines its priority level. The lower the `nice` value, the higher the priority (more CPU time), and vice versa. The `nice` value ranges from -20 (highest priority) to 19 (lowest priority).

- **Changing the `nice` value:**
  To change the priority of a running process, use the `renice` command:
  ```bash
  renice -n 10 -p 1234
  ```
  Here, `-n 10` sets the `nice` value to 10, and `-p 1234` specifies the PID of the process you want to adjust. This command makes the process less aggressive in competing for CPU time.

- **Starting a process with a specific `nice` value:**
  You can start a process with a specific `nice` value using the `nice` command:
  ```bash
  nice -n 5 command
  ```
  Replace `command` with the command you want to run. This starts the process with a `nice` value of 5, giving it a lower priority than normal.

### Using `chrt` for Real-Time Priority

`chrt` (Change Real Time) is used to set or retrieve the real-time scheduling attributes of an existing PID or run a new command with specified real-time attributes. Real-time processes are given more precise control over execution than regular processes.

- **Setting real-time priorities:**
  ```bash
  chrt -f -p 99 1234
  ```
  This sets the process with PID 1234 to a FIFO real-time scheduling policy (`-f`) with the highest real-time priority of 99. High priority values ensure that the process gets more CPU time, suitable for time-sensitive tasks.

- **Running a command with real-time priority:**
  ```bash
  chrt -r 50 command
  ```
  Here, `-r` sets the policy to round-robin, and `50` sets the priority. Replace `command` with the actual command you wish to execute. (Note: when launching a new command you pass the priority directly, without `-p`; the `-p` flag is only used to change an existing process by PID, as in the example above.) This configuration is useful for processes that need consistent CPU cycles.

### Simple Words Explanation

Think of `nice` and `chrt` as ways to tell your computer how important different tasks are. Using `nice` is like setting a general guideline: "This task is not very urgent; let others go first." Using `chrt`, on the other hand, is like telling the system: "This task is super important; make sure it gets what it needs right away."

By adjusting these values, you can fine-tune how your computer allocates its resources, making sure that important tasks get more attention and less critical ones don’t hog resources.

---

## Practical Tips and Scenarios for Using the `top` Command

Effective system monitoring isn't just about knowing the commands; it's also about understanding when and how to use them in various situations. Here, we'll cover some practical scenarios where `top` can be especially useful, along with tips to make the most of its capabilities.

### Scenario 1: Diagnosing System Slowdowns

**Problem:** Your Linux server is responding slowly, and you need to quickly identify the cause.

**Solution:**
1. **Open `top` to identify high CPU or memory-consuming processes.**
   - Start `top` and immediately sort by CPU (`Shift + P`) or memory (`Shift + M`).
2. **Identify any unusual activity.**
   - Look for processes that do not normally consume much resources but are at the top of the list.
3. **Check load averages.**
   - The load averages at the top give you a quick summary of system health over the last 1, 5, and 15 minutes.
4. **Take action based on findings.**
   - If a process is consuming excessive resources and it’s safe to terminate, press `k` to kill the process, entering its PID and signal (usually `15` for a soft kill).

### Scenario 2: Ensuring Critical Processes Are Running

**Problem:** You need to ensure that certain critical applications are always running, such as a database or a web server.

**Solution:**
1. **Filter processes by user or command.**
   - Run `top` with a user filter if the application runs under a specific user: `top -u dbuser`.
   - Alternatively, use `grep` to filter: `top | grep mysqld`.
2. **Regularly check process health.**
   - Look for CPU and memory usage to ensure the process isn't stuck or consuming abnormal resources.
3. **Automate monitoring with alerts.**
   - Set up a simple script that alerts you if the process stops appearing in `top` outputs or exceeds resource usage thresholds.

### Scenario 3: Optimizing Resource Allocation

**Problem:** You need to optimize resource usage to improve server performance during peak times.

**Solution:**
1. **Monitor during peak hours.**
   - Use `top` during peak operational hours to monitor system performance and identify bottlenecks.
2. **Adjust priorities of processes.**
   - Use the `nice` and `renice` commands to adjust priorities of processes. Lower the priority of less critical processes to ensure more CPU time for critical services.
3. **Document baseline performance.**
   - Keep records of performance metrics during different times to help in planning and resource allocation.

### Tips for Long-Term Monitoring

- **Set up `top` in batch mode for periodic monitoring:** Schedule `top` to run at regular intervals and redirect output to a file for historical analysis.
- **Use logging and alerting:** Integrate `top` with system management tools that can log its output and generate alerts based on predefined criteria to proactively manage system health.

---

## Frequently Asked Questions about the `top` Command

### 1. What is the `top` command used for in Linux?

**Answer:** The `top` command is used to display real-time information about the system's running processes, including their CPU and memory usage, priority, and other important metrics. It helps users monitor system performance and manage resources effectively.

### 2. How can I display only the top 10 processes in `top`?

**Answer:** Note that `-n` does *not* limit how many processes are shown — `top -n 10` runs 10 refresh iterations and then exits. To display only the top 10 processes interactively, press `n` while `top` is running, then enter `10` and press Enter. To capture just the top 10 processes non-interactively, combine batch mode with `head` (the first 7 lines are the summary/header, so add 10 to keep 10 process rows):
```bash
top -bn1 | head -n 17
```

### 3. Can I use `top` to monitor CPU temperature?

**Answer:** No, `top` does not provide information about hardware temperatures such as CPU temperature. To monitor CPU temperature, you can use other tools like `lm-sensors` or `psensor`.

### 4. How do I sort processes by memory usage in `top`?

**Answer:** While `top` is running, you can sort processes by memory usage by pressing `Shift + M`. This will reorder the processes so that those using the most memory are listed at the top.

### 5. What does %CPU mean in `top`?

**Answer:** %CPU shows the percentage of the CPU's time that the process is using. This is calculated since the last update and can help identify processes that are consuming too much CPU time.

### 6. How can I kill a process directly from `top`?

**Answer:** To kill a process from within `top`, follow these steps:
1. Note the PID of the process you want to kill.
2. Press `k` in `top`.
3. Enter the PID of the process, and press Enter.
4. Enter the signal you wish to send (typically `15` for a soft kill or `9` for a hard kill), then press Enter.

### 7. Is it possible to filter processes by user in `top`?

**Answer:** Yes, you can filter processes by a specific user by starting `top` with the `-u` option followed by the username:
```bash
top -u username
```
Replace `username` with the actual user name. This will display only the processes owned by that user.

### 8. How do I exit `top`?

**Answer:** To exit `top`, simply press `q`. This will quit the program and return you to the command line.

---
### Conclusion

The `top` command is a powerful tool in the Linux toolkit, essential for anyone responsible for system monitoring and management. Whether you're a new user learning the ropes or a seasoned administrator fine-tuning performance, `top` offers a real-time window into how your system's resources are being utilized. Through its dynamic interface, you can spot problematic processes, adjust priorities, and even terminate applications directly from the interface, helping ensure your Linux environment runs smoothly.

Remember, while `top` is incredibly useful, it's just one part of a full approach to system monitoring. Complementing `top` with other diagnostic tools can provide deeper insights into system performance and health. Here are some additional resources to help you expand your monitoring toolkit and deepen your understanding of Linux system management:

- **htop** - An interactive process viewer, considered an enhanced version of `top`. [Htop Explained](https://hisham.hm/htop/)
- **iotop** - A top-like utility for monitoring disk I/O. [iotop Official Page](http://guichaz.free.fr/iotop/)
- **Glances** - A cross-platform system monitoring tool. [Glances GitHub Repository](https://github.com/nicolargo/glances)
- **Linux Performance** - A site dedicated to Linux performance issues. [Brendan Gregg's Linux Performance](https://www.brendangregg.com/linuxperf.html)

Exploring these tools will equip you with a broader range of options for managing and understanding your systems. Each tool offers unique features and insights, allowing you to tailor your monitoring strategy to meet the specific needs of your environment.

By mastering `top` and its companions, you'll enhance your ability to maintain optimal performance and quickly respond to potential issues before they become critical. Always keep learning and experimenting with new tools as you grow in your Linux administration journey.

---

<a href="https://www.freepik.com/free-vector/process-concept-illustration_11434267.htm#fromView=search&page=1&position=2&uuid=a2d8c663-d86d-46c8-a0f9-4c6c1c3dcfcb" target="_blank" rel="noopener noreferrer">Image by storyset on Freepik</a>
