Skip to content
shellhacks.dev
Linux

Run top Once in Batch Mode for a Shell Script

Run top once and print plain text with top -b -n 1. The first sample has no CPU history, so take -n 2 with a delay and read the second one.

2 min read
Summarize in AI

You want a snapshot of the load and the busiest processes in a script or a log, not an interactive screen.

Shell
top -b -n 1 | head -n 5
echo "--- second sample"
top -b -n 2 -d 1 | awk '/^top -/{n++} n==2' | head -n 5
Text
top - 13:30:46 up 14:53,  0 user,  load average: 0.70, 1.42, 1.39
Tasks:   6 total,   1 running,   5 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :  12952.0 total,    397.4 free,   8416.3 used,   4656.3 buff/cache
MiB Swap:   2048.0 total,    207.2 free,   1840.8 used.   4535.7 avail Mem
--- second sample
top - 13:30:47 up 14:53,  0 user,  load average: 0.64, 1.40, 1.39
Tasks:   7 total,   1 running,   6 sleeping,   0 stopped,   0 zombie
%Cpu(s):  2.5 us,  1.3 sy,  0.0 ni, 95.5 id,  0.1 wa,  0.0 hi,  0.6 si,  0.0 st
MiB Mem :  12952.0 total,    395.7 free,   8417.3 used,   4657.0 buff/cache
MiB Swap:   2048.0 total,    207.2 free,   1840.8 used.   4534.7 avail Mem

-b selects batch mode, which writes ordinary lines without cursor movement, and -n 1 stops after one screen. The CPU line of that first sample in the run was all idle at 100.0, because top has no previous reading to compare against, while the second screen taken one second later showed 2.5 percent user time and 95.5 idle. So a script that wants a real CPU figure asks for -n 2 with -d 1 and keeps the second block. See the top manual.

Batch mode truncates lines to 80 columns unless -w sets a width. The output format changes between procps versions, so parse columns with care, or read /proc yourself. The header lines vary with the machine and are shown here as they came out.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.