1. Overview

In the dynamic world of Linux systems, monitoring and tracking the constantly changing values of CPU usage, memory consumption, and other beneficial metrics is a huge part of system administrators’ daily tasks.

Moreover, Bash provides multiple ways to check different metrics. In particular, one of the most utilized commands is the top command.

In this tutorial, we’ll explore effective methods to keep track of system metric values using the top command, with a focus on simplicity and practicality. Moreover, we’ll also delve into additional commands such as sar and vmstat to broaden our monitoring toolkit.

2. Understanding the Basics

The top command is a robust tool offering insights into the ongoing activities of system processes.

When executed, top continuously updates its display, showcasing an ordered list of processes based on various metrics:

  • CPU usage
  • memory consumption
  • runtime

The values presented by top reflect the current state of the system, constantly refreshing to provide the most up-to-date information:

$ top
 PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
12345 user      20   0   200M   50M   40M R   25.0  2.5   0:10.00 example_process

For example, the %CPU column indicates the percentage of CPU usage by each process, and as processes run, this value fluctuates accordingly. Similarly, the %MEM column reveals the percentage of system memory utilized by each process, with values changing dynamically as processes allocate or release memory.

top offers administrators a real-time window into the dynamic behavior of their system, enabling them to identify resource-intensive processes and respond promptly to changing performance conditions.

3. Keeping Track of Values

Since the output of the top command keeps changing over time, some administrators are in favor of capturing the output and saving it to a file.

Moreover, there isn’t a specific time interval designated for updating values and displaying the latest system utilization. Particularly, this differs from one system to another depending on the resources consumed. Regardless, every change in values is called a new iteration for the top command.

In this section, we’ll see a couple of methods to capture the output of a certain iteration at a specific point in time and save it for later use in a different file.

3.1. Enabling Batch Mode

The top command offers a batch mode that enables us to run a single iteration and capture the output in a file.

Let’s delve into the basic command:

$ top -b -n 1 >> file.txt

Next, we’ll understand the options above:

  • -b enables the batch mode
  • -n 1 specifies a single iteration of the top command’s output
  • we use >> for redirection and creation of a new file

Basically, the batch mode doesn’t accept further input and runs until the iteration limit we’ve set with the -n command-line option, which is one iteration in our case.

Next, let’s check the output by showing the content of file.txt:

$ cat file.txt
top - 15:35:10 up  2:17,  2 users,  load average: 0.15, 0.25, 0.30
Tasks: 216 total,   1 running, 215 sleeping,   0 stopped,   0 zombie
%Cpu(s):  3.2 us,  1.8 sy,  0.0 ni, 94.7 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  4040236 total,  1883908 free,  1233544 used,   921784 buff/cache
KiB Swap:  2097148 total,  2097148 free,        0 used.  2575260 avail Mem
 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
12345 user 20 0 512M 128M 96M R 10.5 3.2 0:05.00 myprocess

Here, we see the CPU usage breakdown, memory information, and more.

3.2. Filter by Process

From the perspective of an administrator, we don’t only utilize the top command to get insights on the processes consuming the most resources, we also tend to use it to check the operation of a specific process.

For instance, an administrator might be interested in knowing the init command’s participation in resource consumption:

$ top -b -n 1 | grep init
  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
    1 root      20   0   60140   7412   5968 S   6.0  0.2   0:04.80 init

In the above example, we use the pipe | symbol to redirect the output of one command as the input to another providing us with a seamless flow of data. In addition, the grep command filters for the word init and displays its participation in the system’s resources.

Furthermore, we can extract specific values for that process, such as CPU usage, using awk. For instance, we can get the ninth (9) column (CPU value) for the init process:

$ top -b -n 1 | grep "init" | head -1 | awk '{print $9}'
6.0

We use the entire command in conjunction with the top command, which provides real-time information about system processes:

  • head -1: selects only the first line of the top output, which often contains overall system statistics
  • awk ‘{print $9}’: extracts the ninth column from that first line, which usually represents the system-wide CPU usage percentage

If we compare the previous two snippets, the output again presents a value of 6.0, which is the value under the %CPU column of the top command.

3.3. Filter by Resource

Alternatively, to automate value retrieval, we can initialize two variables called CPU and MEM:

$ CPU=$(top -b -n1 | grep "myprocess" | head -1 | awk '{print $9}')
$ MEM=$(top -b -n1 | grep "myprocess" | head -1 | awk '{print $10}')

Then, we get the output by utilizing the echo command:

$ echo "CPU Usage: $CPU%"
$ echo "Memory Usage: $MEM%"

At the end, we present multiple representations for meeting the same objective.

4. Expanding Monitoring Horizons

In this section, we’ll explore other alternatives for the top command.

4.1. Using sar Command

The sar command is a powerhouse for collecting, reporting, and saving system activity information. By default, it captures various metrics at regular intervals.

To begin with, we get CPU usage for the next ten seconds:

$ sar -u 10 2
Linux 5.4.0-88-generic (hostname)  11/12/23  _x86_64_ (4 CPU)
10:00:01 AM     CPU     %user     %nice   %system   %iowait    %steal     %idle
10:10:01 AM     all      2.41      0.00      1.01      0.39      0.00     96.18
10:20:01 AM     all      1.65      0.00      0.70      0.27      0.00     97.38

Now, let’s break down the command and its output:

  • -u specifies CPU usage
  • 10 is the sampling interval in seconds
  • 2 specifies the number of samples

Thus, the output details CPU usage over time, breaking it down by usage percentages.

4.2. Using vmstat Command

The vmstat command provides a snapshot of system statistics, including memory, swap, and CPU usage.

Let’s see how to monitor every 5 seconds for a total of 3 iterations:

$ vmstat 5 3
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 0  0      0 987652 102040 512348    0    0     0     0  456  789 10  5 85  0  0
 1  0      0 976512 102044 511240    0    0   120    12  520  920 15  7 78  0  0

Finally, this output presents a comprehensive overview, including memory, swap, and CPU statistics.

4.3. Custom Comparison

As we noticed, the output representation of each command differs from the others. Although some output is persistent across all three methods, such as the CPU utilization parameter, there are differences. Therefore, we’ll explore how to combine a script that aims to present the three outputs of top, sar, and vmstat, so we can compare them.

Let’s create a shell script that combines top, sar, and vmstat to provide a holistic view of system performance:

$ cat monitor.sh
#!/bin/bash
top_output=$(top -b -n 1 | grep "myprocess" | head -1)
sar_output=$(sar -u 1 1 | tail -n 1)
vmstat_output=$(vmstat 1 1 | tail -n 1)

echo "Top Output:"
echo "$top_output"
echo "Sar Output:"
echo "$sar_output"
echo "Vmstat Output:"
echo "$vmstat_output"

Above, we see the content of the monitor.sh script. Specifically, this script fetches the top output for a specific process, sar output for CPU usage, and vmstat output for system statistics.

Let’s see the output of executing the monitor.sh script:

$ sudo bash monitor.sh
Top Output:
  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
12345 user      20   0  100.0g  10.2g  90.1g S   5.2  2.5  30:00.00 myprocess
Sar Output:
 12:00:01 PM     CPU     %user     %nice   %system   %iowait    %steal     %idle
             all      8.33      0.00      2.16      0.33      0.00     89.18
Vmstat Output:
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 0  0      0 987652 102040 512348    0    0     0     0  456  789 10  5 85  0  0

After running the script, we see a consolidated view, combining process-specific details, CPU usage, and system statistics.

5. Conclusion

In this article, we’ve explored practical ways to keep track of Linux system values using top and extended our monitoring toolkit with commands like sar and vmstat.

From basic batch mode usage to advanced shell scripting and external tools, we’ve discussed a spectrum of approaches. By understanding these methods, we empower ourselves to effectively monitor and manage our Linux systems in a dynamic environment.