Basic Process Monitoring from Bash
Process monitoring answers practical questions about the programs running on a machine: Is my service still running? Which process is using all the CPU? How much memory does this job take, and is it growing? Is the system overloaded? Full monitoring systems such as Prometheus or Nagios answer these questions continuously for many machines, but on a single machine, during debugging, or inside an automation script, a few standard commands and a short Bash loop are often all you need.
This lesson covers the tools that read process information (ps, pgrep, pstree and the /proc file system), the commands that describe the whole system (uptime, free, top), how CPU and memory figures are actually measured, and how to combine them in a script that watches one process over time. The examples were run on Ubuntu 24.04 with procps-ng 4.0.4, which provides ps, pgrep, top and free on most Linux systems.
Where Process Information Comes From
On Linux, the kernel publishes information about every process as files under /proc: the folder /proc/1234 describes process 1234. These are not real files on a disk. Reading them asks the kernel for the current values, so their content changes from one read to the next. ps, top and pgrep are all programs that read /proc and format the result.
A Bash script can use the programs or read /proc directly. The programs are easier and more portable; /proc gives access to details the programs do not show and avoids starting an extra process for every measurement.
Listing Processes with ps
ps prints a snapshot of processes. Without options it shows only the processes of the current terminal, which is rarely what a script needs. Two classic forms list every process on the system:
ps aux | head -1
ps -ef | head -1
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
UID PID PPID C STIME TTY TIME CMD
ps aux (BSD style, no dash) shows CPU and memory percentages; ps -ef (POSIX style) shows the parent process ID. Both are good for reading on screen. For scripts, it is better to choose the columns yourself.
Choosing Columns with -o
-o takes a comma-separated list of column names, and -p selects processes by PID. The test script started a sleep 300 and a busy loop in the background:
sleep 300 & s=$!
bash -c 'while :; do :; done' & busy=$!
sleep 1
ps -o pid,ppid,user,stat,etime,args -p "$s,$busy"
PID PPID USER STAT ELAPSED COMMAND
1020 1018 root S 00:01 sleep 300
1021 1018 root R 00:01 bash -c while :; do :; done
The most useful columns:
| Column | Meaning |
|---|---|
pid, ppid | process ID and parent process ID |
user | owner of the process |
stat | state: R running, S sleeping, D waiting for disk, T stopped, Z zombie |
etime, etimes | elapsed time since the process started (etimes in seconds) |
pcpu | CPU usage in percent (see the warning below) |
rss | resident memory: physical RAM in use, in kilobytes |
pmem | rss as a percentage of total RAM |
comm | the program name only |
args | the full command line |
Adding = after a column name removes its header, which is what a script usually wants. A single value can then be captured directly:
ps -o pid=,rss=,comm= -p "$s"
ps -o etimes= -p "$s"
1020 1752 sleep
1
ps pads values with spaces; $(( )) or read removes them when the value is used in a script.
Selecting and Sorting
Other ways to select processes include -C NAME (by program name), -u USER (by owner) and --ppid PID (children of a process). --sort orders the output; a leading - means descending:
ps -C sleep -o pid,args
ps --ppid $$ -o pid,rss,pmem,comm --sort=-rss
PID COMMAND
1020 sleep 300
PID RSS %MEM COMMAND
1178 62208 0.7 python3
1182 4316 0.0 ps
1177 3444 0.0 bash
1176 1768 0.0 sleep
The second command listed the children of the test script, largest memory user first: a Python process holding about 50 MB of data, the ps command itself, a bash and a sleep. On a real system, ps -eo pid,pcpu,rss,comm --sort=-pcpu | head lists the top CPU users and --sort=-rss the top memory users.
Finding Processes by Name: pgrep and pidof
When you know the program name but not the PID, pgrep searches for it (lesson 140 used its sibling pkill):
pgrep -a sleep
pgrep -c bash
pidof sleep
1020 sleep 300
3
1020
pgrep NAMEprints matching PIDs, one per line;-aadds the command line,-cprints only the count,-xrequires the whole name to match, and-fmatches against the full command line.pidof NAMEprints the PIDs of an exact program name on one line.- Both return status 1 when nothing matches, so they work directly in conditions:
if pgrep -x nginx > /dev/null; then echo "nginx is running"; fi
Matching by name can find more processes than you expect, for example the same program started by another user. When a script started the process itself, the saved PID from $! is more precise (lesson 139).
Showing Parent and Child Relationships
pstree (from the psmisc package) draws processes as a tree. -p adds the PIDs:
pstree -p $$
bash(1170)-+-bash(1177)---sleep(1180)
|-pstree(1181)
|-python3(1178)
`-sleep(1176)
The script (1170) had four children; one of them, a bash -c shell, had started a sleep of its own. This view is useful when stopping a group of related processes, because killing a parent does not automatically end its children (lessons 139 and 141).
Reading /proc Directly
Each process folder contains many files. Three are particularly useful:
grep -E '^(Name|State|PPid|VmRSS|Threads)' /proc/$s/status
tr '\0' ' ' < /proc/$s/cmdline; echo
readlink /proc/$s/cwd
Name: sleep
State: S (sleeping)
PPid: 1215
VmRSS: 1764 kB
Threads: 1
sleep 300
/home/ana/app
(This test started its sleep from the folder /home/ana/app.)
statusis readable text, oneKey: valueper line.VmRSSis the resident memory, the same figure as thersscolumn ofps.cmdlineholds the command-line arguments separated by NUL bytes, sotrturns them into spaces.cwdis a link to the process's current working directory;exepoints to the program file andfd/lists its open files. Reading these for another user's process requires root.
Parsing /proc/PID/stat Safely
/proc/PID/stat holds the same information as one line of numbers, including the CPU time used. The second field is the program name in parentheses, and that name may contain spaces. A program copied to the file name my sleep shows the problem:
cp /usr/bin/sleep "./my sleep"
"./my sleep" 30 & p=$!
sleep 0.2
cut -d' ' -f1-5 /proc/$p/stat
read -ra f < /proc/$p/stat; echo "naive third field: ${f[2]}"
s=$(< /proc/$p/stat); s=${s##*) }; read -ra f <<< "$s"; echo "state=${f[0]} utime=${f[11]} stime=${f[12]}"
1194 (my sleep) S 1192
naive third field: sleep)
state=S utime=0 stime=0
Splitting the whole line on spaces shifted every field after the name: what should have been the state was sleep). The safe method removes everything up to the last ) with ${s##*) } (lesson 54), so the remaining fields always start with the state. Fields 14 and 15 of the original line, the user and system CPU time, are then at indexes 11 and 12.
How Busy Is the System?
Load Average
uptime
cat /proc/loadavg
nproc
03:54:48 up 9 min, 0 user, load average: 0.02, 0.04, 0.00
0.02 0.04 0.00 1/102 1042
2
The load average is the average number of processes that were running or waiting to run (on Linux, also those waiting for disk) over the last 1, 5 and 15 minutes. It must be compared with the number of CPUs from nproc: on this 2-CPU machine, a load of 2.0 would mean both CPUs fully used, and a load above 2.0 would mean processes waiting for a turn. /proc/loadavg contains the same three numbers, plus the number of running and total processes and the most recent PID, and is easy to read with read.
Memory
free -h
total used free shared buff/cache available
Mem: 7.8Gi 488Mi 7.4Gi 12Mi 183Mi 7.4Gi
Swap: 0B 0B 0B
The column to watch is available: the memory that new programs can use without the system having to swap. free counts memory used for the file cache (buff/cache) as in use, but the kernel gives it back when programs need it, so a low free figure alone is not a problem. -h chooses readable units; -m gives plain megabytes for scripts.
A Snapshot from top
top normally runs as a full-screen program. In batch mode, -b, it writes plain text, and -n 1 makes it stop after one update, which makes it usable in scripts and logs:
top -b -n 1 | head -5
top - 03:54:48 up 9 min, 0 user, load average: 0.02, 0.04, 0.00
Tasks: 68 total, 1 running, 66 sleeping, 0 stopped, 1 zombie
%Cpu(s): 0.0 us, 0.0 sy, 0.0 ni, 95.2 id, 4.8 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 8023.6 total, 7565.3 free, 488.2 used, 184.3 buff/cache
MiB Swap: 0.0 total, 0.0 free, 0.0 used. 7535.4 avail Mem
The %Cpu(s) line splits CPU time into user (us), system (sy), idle (id), waiting for disk (wa) and a few others. A high wa value points to a disk or network storage bottleneck rather than a lack of CPU. Below these lines, top lists processes sorted by CPU usage.
For repeated views while you watch, watch -n 2 'ps -o pid,pcpu,rss,args -C nginx' reruns a command every 2 seconds and redraws the screen. Inside a script, a loop with sleep does the same job and can also act on the values.
What %CPU in ps Really Means
The pcpu column of ps is not the current CPU usage. It is the CPU time the process has used since it started, divided by the time it has existed. A process that was busy earlier and is idle now still shows a high value:
# busy for 2 seconds, then idle
bash -c 'end=$(( ${EPOCHREALTIME/./} + 2000000 ))
while (( ${EPOCHREALTIME/./} < end )); do :; done
sleep 30' &
p=$!
sleep 4
ps -o pid,pcpu,etimes -p "$p"
cpu_ticks() { # CPU time of PID $1 in clock ticks (user + system)
local f
read -ra f < "/proc/$1/stat"
echo $(( f[13] + f[14] ))
}
t1=$(cpu_ticks "$p"); sleep 1; t2=$(cpu_ticks "$p")
echo "CPU ticks used in the last second: $(( t2 - t1 ))"
kill "$p"
PID %CPU ELAPSED
1200 49.8 4
CPU ticks used in the last second: 0
ps reported 49.8 percent, because the process had been busy for 2 of its 4 seconds, while it actually used no CPU at all during the last second. (cpu_ticks here uses the simple split, which is fine for a program named bash; the complete example uses the safe form.)
To measure current usage, read the CPU time twice and divide the difference by the time between the reads. CPU time in /proc is counted in clock ticks; getconf CLK_TCK gives the number of ticks per second, which is 100 on practically all Linux systems:
CPU percent = (ticks2 - ticks1) / CLK_TCK / seconds between reads * 100
A process that uses one CPU completely shows 100 percent; a multi-threaded program can show more than 100 on a machine with several CPUs. top uses the same method between its updates.
A Complete Example: Watching One Process
procwatch.sh samples one process at a fixed interval and prints its current CPU usage and memory. It warns when memory goes above a limit (and again when it falls back below), can write a CSV log for later analysis, and prints a final report when the process ends or when the user presses Ctrl + C.
#!/usr/bin/env bash
# procwatch.sh [-i SECONDS] [-m MAX_MB] [-l CSV_FILE] PID
# Sample the CPU and memory use of PID until it ends (or Ctrl+C), warn
# when its memory (RSS) goes above MAX_MB, and print a final report.
# Linux only: reads /proc.
set -uo pipefail
prog=${0##*/}
interval=1 max_mb=0 csv=
usage() { echo "usage: $prog [-i SECONDS] [-m MAX_MB] [-l CSV_FILE] PID" >&2; exit 2; }
while getopts ':i:m:l:' opt; do
case $opt in
i) interval=$OPTARG ;;
m) max_mb=$OPTARG ;;
l) csv=$OPTARG ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# == 1 )) || usage
pid=$1
[[ $pid =~ ^[1-9][0-9]*$ ]] || { echo "$prog: not a PID: $pid" >&2; exit 2; }
[[ $interval =~ ^[0-9]+(\.[0-9]+)?$ ]] || { echo "$prog: -i: invalid interval: $interval" >&2; exit 2; }
[[ $max_mb =~ ^[0-9]+$ ]] || { echo "$prog: -m: need whole megabytes" >&2; exit 2; }
[[ -r /proc/$pid/stat ]] || { echo "$prog: $pid: no such process" >&2; exit 1; }
hz=$(getconf CLK_TCK) # clock ticks per second, usually 100
name=$(< "/proc/$pid/comm")
# cpu_ticks PID: user + system CPU time in clock ticks
cpu_ticks() {
local s f
s=$(< "/proc/$1/stat") || return 1
s=${s##*) } # drop "PID (name) ": the name may contain spaces
read -ra f <<< "$s"
echo $(( f[11] + f[12] )) # fields 14 (utime) and 15 (stime)
}
# rss_kb PID: resident memory in kB (empty for a process that is ending)
rss_kb() {
local key value rest
while read -r key value rest; do
[[ $key == VmRSS: ]] && { echo "$value"; return 0; }
done < "/proc/$1/status"
return 1
}
samples=0 cpu_sum=0 peak_kb=0 over=0
started=${EPOCHREALTIME/./}
report() {
local secs=$(( (${EPOCHREALTIME/./} - started) / 1000000 ))
local avg=0
(( samples > 0 )) && avg=$(( cpu_sum / samples ))
printf '%s: %s (%s) watched for %ss, %d samples, peak RSS %d MB, average CPU %d.%d%%\n' \
"$prog" "$pid" "$name" "$secs" "$samples" $(( peak_kb / 1024 )) $(( avg / 10 )) $(( avg % 10 ))
}
trap 'echo; report; exit 130' INT
[[ -n $csv ]] && echo "time,pid,cpu_percent,rss_kb" > "$csv"
printf '%-8s %7s %9s\n' TIME CPU% RSS_MB
prev_ticks=$(cpu_ticks "$pid") prev_t=${EPOCHREALTIME/./}
while sleep "$interval"; do
ticks=$(cpu_ticks "$pid" 2>/dev/null) && kb=$(rss_kb "$pid" 2>/dev/null) || break
now=${EPOCHREALTIME/./}
# CPU % in tenths: CPU ticks used / ticks available in the elapsed time
tenths=$(( (ticks - prev_ticks) * 1000 * 1000000 / (hz * (now - prev_t)) ))
prev_ticks=$ticks prev_t=$now
(( samples++, cpu_sum += tenths ))
(( kb > peak_kb )) && peak_kb=$kb
printf '%(%H:%M:%S)T %5d.%d %9d\n' -1 $(( tenths / 10 )) $(( tenths % 10 )) $(( kb / 1024 ))
[[ -n $csv ]] && printf '%(%F %T)T,%s,%d.%d,%s\n' -1 "$pid" $(( tenths / 10 )) $(( tenths % 10 )) "$kb" >> "$csv"
if (( max_mb > 0 && kb > max_mb * 1024 && !over )); then
echo "$prog: WARNING: $pid ($name) uses $(( kb / 1024 )) MB, above the ${max_mb} MB limit" >&2
over=1
elif (( over && kb <= max_mb * 1024 )); then
echo "$prog: $pid ($name) is back under ${max_mb} MB" >&2
over=0
fi
done
echo "$prog: process $pid has ended"
report
How It Works
- Validation rejects anything that is not a positive number as a PID, checks the interval and the limit, and confirms that
/proc/PID/statexists before the loop starts. cpu_ticksuses the safe parsing shown earlier, so a program name with spaces or parentheses cannot shift the fields. It returns a failure status when the process has disappeared.rss_kbreads/proc/PID/statusline by line withread -r key value rest, which splits each line into the key, the number and the unit. A process that has ended but not yet been collected by its parent (a zombie) has noVmRSSline, so the function fails and the loop stops.- CPU usage is calculated from two consecutive readings, as described above. The real elapsed time comes from
EPOCHREALTIMEin microseconds, becausesleep 1plus the time spent in the loop is always a little more than one second. All arithmetic is in integers: the result is in tenths of a percent and printed aswhole.tenth. while sleep "$interval"pauses between samples;sleepaccepts fractions such as0.5. The loop ends withbreakas soon as either reading fails, which means the process is gone.printf '%(%H:%M:%S)T' -1prints the current time without running the externaldatecommand (lesson 115). The CSV log uses the full date.- The warning is printed once when memory crosses the limit, not on every sample; the
overflag remembers the state, and a second message reports when memory falls back below the limit. - The INT trap prints the report when the user stops watching with Ctrl + C, and ends with status 130.
Running the Complete Example
The first test watched a Python program that adds 20 MB of data every second and keeps one CPU busy for half of each second:
# grow.py
import time
data = []
for i in range(6):
data.append(b'x' * 20 * 1024 * 1024) # 20 MB more each round
t = time.time()
while time.time() - t < 0.5: # busy for half a second
pass
time.sleep(0.5) # idle for half a second
python3 grow.py & p=$!
bash procwatch.sh -m 80 -l usage.csv "$p"; echo "status $?"
cat usage.csv
TIME CPU% RSS_MB
03:55:39 50.7 30
03:55:40 50.7 50
03:55:41 50.7 70
03:55:42 50.8 90
procwatch.sh: WARNING: 1087 (python3) uses 90 MB, above the 80 MB limit
03:55:43 50.7 110
03:55:44 51.7 130
procwatch.sh: process 1087 has ended
procwatch.sh: 1087 (python3) watched for 7s, 6 samples, peak RSS 130 MB, average CPU 50.8%
[1]+ Done python3 grow.py
status 0
time,pid,cpu_percent,rss_kb
2026-11-24 03:55:39,1087,50.7,31436
2026-11-24 03:55:40,1087,50.7,51916
2026-11-24 03:55:41,1087,50.7,72396
2026-11-24 03:55:42,1087,50.8,92876
2026-11-24 03:55:43,1087,50.7,113356
2026-11-24 03:55:44,1087,51.7,133836
The CPU figure matched the program's behavior, about half of one CPU, and memory grew by 20 MB per sample. The Done line is printed by the test script's Bash for its background job.
The second test used a program that holds 100 MB for about two seconds and then frees it:
# spike.py
import time
time.sleep(1.2)
data = b'x' * 100 * 1024 * 1024 # 100 MB for about 2 seconds
time.sleep(2)
del data
time.sleep(2)
TIME CPU% RSS_MB
03:55:54 0.9 10
03:55:55 6.9 110
procwatch.sh: WARNING: 1119 (python3) uses 110 MB, above the 50 MB limit
03:55:56 0.0 110
03:55:57 0.0 10
procwatch.sh: 1119 (python3) is back under 50 MB
03:55:58 0.0 10
procwatch.sh: process 1119 has ended
procwatch.sh: 1119 (python3) watched for 6s, 5 samples, peak RSS 110 MB, average CPU 1.5%
The warning appeared once, and the recovery was reported when the memory was released.
Watching a sleep 30 with half-second samples and pressing Ctrl + C after about 1.5 seconds printed the report early:
$ bash procwatch.sh -i 0.5 1147
TIME CPU% RSS_MB
03:56:00 0.0 1
03:56:00 0.0 1
03:56:01 0.0 1
^C
procwatch.sh: 1147 (sleep) watched for 1s, 3 samples, peak RSS 1 MB, average CPU 0.0%
$ echo "status $?"
status 130
Invalid input is rejected before any sampling starts:
bash procwatch.sh 999999; echo "status $?"
bash procwatch.sh abc; echo "status $?"
bash procwatch.sh -i x 1; echo "status $?"
bash procwatch.sh -m 1.5 1; echo "status $?"
bash procwatch.sh 1 2; echo "status $?"
procwatch.sh: 999999: no such process
status 1
procwatch.sh: not a PID: abc
status 2
procwatch.sh: -i: invalid interval: x
status 2
procwatch.sh: -m: need whole megabytes
status 2
usage: procwatch.sh [-i SECONDS] [-m MAX_MB] [-l CSV_FILE] PID
status 2
The same loop structure extends naturally: watching a process by name with pgrep, restarting a service when it disappears, or sending a notification instead of printing a warning. Lessons 167 and 172 build on it for system-wide CPU, memory and health checks.