Monitoring CPU, Memory, and System Load

Su Suriya Ravichandran Updated 06 Dec 2026
18 min read ·Lesson 167 of 205

When a server becomes slow, the first questions are always the same: Is the CPU busy? Is the machine short of memory? Are processes waiting in line to run? Lesson 143 looked at individual processes with ps, pgrep and top. This lesson looks at the whole system: how Linux measures CPU use, what the load average really counts, which memory figure tells you whether the machine is running out, and how a Bash script can read these numbers directly from the kernel and raise a warning when they cross a limit.

Almost every monitoring tool on Linux, from top and free to large monitoring agents, reads the same small set of files in the /proc file system. /proc is not stored on disk; the kernel generates its files on the fly when they are read. A Bash script can read them as easily as any text file, without installing anything.

What you want to knowSource
Number of CPUsnproc
CPU time spent working and idle/proc/stat
Load averages/proc/loadavg (also shown by uptime)
Memory and swap/proc/meminfo (also shown by free)
How long tasks wait for CPU, memory or disk/proc/pressure/cpu, memory, io

CPU Usage

How Linux counts CPU time

A CPU is either running something or idle; there is no "half busy" at any single instant. A CPU percentage is therefore always an average over a period: of the last 2 seconds, how much time was spent working?

The kernel keeps running totals of CPU time since boot in the first line of /proc/stat, measured in clock ticks (usually 100 per second; getconf CLK_TCK shows the value):

head -1 /proc/stat
cpu  12534 0 22685 88716 105 0 119 481 0 0

The first line, labelled cpu, adds up all CPUs. Lines cpu0, cpu1 and so on follow for each CPU. The numbers are, in order:

FieldMeaning
userrunning ordinary program code
nicerunning program code with a lowered priority (nice)
systemrunning kernel code on behalf of programs
idledoing nothing
iowaitidle while some task waits for disk I/O
irq, softirqhandling hardware and software interrupts
stealtime a virtual machine wanted the CPU but the host gave it to another guest
guest, guest_nicerunning virtual machines (already included in user and nice)

Because the numbers only grow, one reading by itself says nothing about the present. You read the file twice, a few seconds apart, and compare the differences: busy time ÷ total time over that interval. iowait counts as idle time (the CPU could have run something else), and guest and guest_nice are left out because they are already part of user and nice.

Measuring CPU use from Bash

# cpu_sample: print "busy total" jiffies from the first line of /proc/stat
cpu_sample() {
    local label user nice system idle iowait irq softirq steal
    read -r label user nice system idle iowait irq softirq steal _ < /proc/stat
    echo "$(( user + nice + system + irq + softirq + steal )) \
$(( user + nice + system + idle + iowait + irq + softirq + steal ))"
}
read -r busy1 total1 < <(cpu_sample)
sleep 1
read -r busy2 total2 < <(cpu_sample)
echo "busy jiffies: $(( busy2 - busy1 )), total jiffies: $(( total2 - total1 ))"
echo "CPU busy: $(( 100 * (busy2 - busy1) / (total2 - total1) ))%"

read reads only the first line of the file, splits it into the named variables, and puts any remaining fields into _, a throwaway variable. ("Jiffies" is the kernel's name for these ticks.) On an idle machine with 2 CPUs:

busy jiffies: 0, total jiffies: 199
CPU busy: 0%

In one second, two CPUs provide about 200 ticks. With one busy process (yes > /dev/null &) running:

busy jiffies: 102, total jiffies: 202
CPU busy: 50%

One process can keep only one CPU busy, so on a 2-CPU machine it shows as 50%. This matters when you read tools: top shows a process using one full CPU as 100%, while system-wide figures, like this one, are percentages of all CPUs together.

Reading the result

High CPU use is not a problem by itself; a build server or video encoder is supposed to use all its CPUs. It becomes a problem when it lasts and work starts to queue, which is what the load average shows. Two other fields deserve attention: a high iowait means the CPUs are waiting for the disk, not working, and on virtual machines a high steal means the host is overcommitted, which no change inside the virtual machine can fix.

The Load Average

uptime prints how long the system has been running and three load averages:

uptime
cat /proc/loadavg
nproc
 15:03:01 up 10 min,  0 user,  load average: 2.23, 1.19, 0.50
2.23 1.19 0.50 1/109 1343
2

The three numbers are averages over roughly the last 1, 5 and 15 minutes. /proc/loadavg adds two more fields: 1/109 means 1 task was running at that instant out of 109 that exist, and 1343 is the most recently created process ID.

What the load counts

The load is the average number of tasks that are running or ready to run (waiting for a CPU). On Linux, it also counts tasks in uninterruptible sleep, usually waiting for disk or network storage. So:

  • On a machine with 2 CPUs, a load of 2.0 means that, on average, both CPUs were fully used and nothing had to wait.
  • A load of 4.0 on the same machine means that, on average, two tasks were waiting for every task running.
  • A load of 1.0 on a 16-CPU machine is almost nothing.

The load must therefore always be compared with the number of CPUs (nproc). Dividing the load by the CPU count gives the load per CPU; values that stay above 1.0 mean work is queuing. Because disk waits are included, a high load with low CPU use usually points at slow storage rather than busy CPUs.

The averages are exponentially damped: recent seconds count more, but old activity fades slowly. The output above was taken right after a test that had kept the CPUs busy: the system was already idle, yet the 1-minute load was still 2.23. For alerts, the 5-minute value is a good compromise: it ignores short spikes but reacts within minutes.

Memory

free and /proc/meminfo

free -h
               total        used        free      shared  buff/cache   available
Mem:           7.8Gi       588Mi       7.1Gi        12Mi       357Mi       7.3Gi
Swap:             0B          0B          0B

The most important column is available, not free. Linux uses otherwise unused memory as a page cache, which keeps recently read file data in memory so it does not have to be read from disk again. This shows as buff/cache. When a program needs memory, the kernel simply drops cached data. So memory used by the cache is, for the most part, still available. A machine that shows little free memory but plenty available memory is healthy; Linux is just making good use of RAM.

free takes its figures from /proc/meminfo, which a script can read directly. Values are in KiB:

grep -E '^(MemTotal|MemFree|MemAvailable|Buffers|Cached|SwapTotal|SwapFree):' /proc/meminfo
MemTotal:        8216208 kB
MemFree:         7485776 kB
MemAvailable:    7613476 kB
Buffers:           13488 kB
Cached:           343320 kB
SwapTotal:             0 kB
SwapFree:              0 kB

MemAvailable is the kernel's own estimate of how much memory new programs can use without the system starting to swap. It accounts for which cached pages can actually be dropped. Scripts should use it rather than trying to add up MemFree, Buffers and Cached; that sum overestimates, because not every cached page can be freed.

Swap and the OOM killer

Swap is disk space used as an overflow for memory. When RAM runs short, the kernel moves pages that have not been used recently to swap. A little swap use is normal. Heavy and growing swap use, together with low MemAvailable, means the machine needs more memory than it has, and it slows down sharply because the disk is thousands of times slower than RAM. Many cloud servers and containers have no swap at all (SwapTotal: 0).

When neither RAM nor swap can satisfy a request, the Linux out-of-memory (OOM) killer ends a process to free memory, usually the one using the most. When this lesson's examples were tested, three Python processes allocating 2.45 GB each on an 8 GB machine triggered it, and Bash reported one of them as killed:

t5.sh: line 6:  1390 Killed                  python3 /srv/t167/hog.py 2450000000 20

The kernel log (journalctl -k or dmesg, with root rights) records each OOM kill. A memory check aims to warn before this point.

Processes using the most memory

ps can sort by resident set size (RSS), the amount of RAM a process is actually using, in KiB:

ps -eo pid,user,rss,pmem,comm --sort=-rss | head -n 4

The pmem column is RSS as a percentage of total memory. Shared libraries are counted in the RSS of every process that uses them, so the RSS values of many processes added together can exceed the memory in use.

Other Views: vmstat and Pressure Stall Information

vmstat prints a compact line of system statistics every interval. vmstat 1 3 prints three lines, one second apart:

procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st gu
 0  0      0 7485776  13488 353100    0    0   407   420  252    1 10 18 71  0  0  0
 0  0      0 7485776  13488 353140    0    0     0     0   96  114  1  0 100  0  0  0
 0  0      0 7485776  13488 353140    0    0     0     0   93  118  0  0 100  0  0  0

The first line is an average since boot; only the following lines describe the present. Useful columns are r (tasks running or waiting for a CPU), b (tasks blocked on I/O), si/so (memory swapped in and out per second; steady non-zero values mean the machine is short of memory) and us, sy, id, wa, st (user, system, idle, I/O wait and steal, in percent).

Newer kernels (4.20 and later, when enabled) also provide Pressure Stall Information in /proc/pressure/. Instead of asking how busy a resource is, it measures how much time tasks were delayed because the resource was short:

cat /proc/pressure/cpu
some avg10=19.43 avg60=33.85 avg300=18.56 total=83661941
full avg10=0.00 avg60=0.00 avg300=0.00 total=0

some avg60=33.85 means that, over the last 60 seconds, at least one task was waiting for a CPU 33.85% of the time; this was measured while three busy processes competed for two CPUs. full counts time when all non-idle tasks were stalled at once. The same format exists for memory and io. Pressure values answer "is anyone actually suffering?" more directly than utilization, and a script can read them the same way as the other files.

A Complete Example: A System Load Check

sysload-check.sh measures CPU use over a short interval, compares the 5-minute load per CPU, available memory and swap use with limits, prints one line per check, and can list the processes responsible when something is wrong.

#!/usr/bin/env bash
#
# sysload-check.sh - check CPU use, load average, memory and swap
#
# Usage: sysload-check.sh [-i SECONDS] [-c CPU%] [-l LOAD] [-m MEM%] [-s SWAP%] [-p]
#   -i SECONDS  how long to measure CPU use (default: 2)
#   -c CPU%     warn when CPU use is at least this percent (default: 90)
#   -l LOAD     warn when the 5-minute load per CPU is at least this,
#               e.g. 1.5 (default: 1.0)
#   -m MEM%     warn when available memory is below this percent (default: 10)
#   -s SWAP%    warn when swap use is at least this percent (default: 50)
#   -p          on a CPU/load or memory/swap warning, also list the
#               processes using the most CPU or memory
#
# Exit status: 0 OK, 1 WARNING, 3 UNKNOWN (bad options or unreadable /proc)

set -uo pipefail

interval=2 cpu_warn=90 load_warn=1.0 mem_warn=10 swap_warn=50 show_procs=0
status=0
cpu_problem=0 mem_problem=0

die()   { echo "${0##*/}: $*" >&2; exit 3; }
usage() { echo "usage: ${0##*/} [-i SECONDS] [-c CPU%] [-l LOAD] [-m MEM%] [-s SWAP%] [-p]" >&2; exit 3; }

# report NAME OK|WARNING TEXT: print one aligned result line
report() {
    printf '%-7s %-8s %s\n' "$1" "$2" "$3"
    [[ $2 == WARNING ]] && status=1
    return 0
}

# hundredths 1.5 -> 150: turn a number with up to two decimals into an integer
hundredths() {
    local whole=${1%%.*} frac=
    [[ $1 == *.* ]] && frac=${1#*.}
    frac=${frac}00
    echo $(( 10#$whole * 100 + 10#${frac:0:2} ))
}

# cpu_sample: print "busy total" CPU time (in clock ticks) since boot
cpu_sample() {
    local label user nice system idle iowait irq softirq steal
    read -r label user nice system idle iowait irq softirq steal _ < /proc/stat ||
        die "cannot read /proc/stat"
    echo "$(( user + nice + system + irq + softirq + steal ))" \
         "$(( user + nice + system + idle + iowait + irq + softirq + steal ))"
}

# meminfo KEY: print one value (in KiB) from /proc/meminfo
meminfo() {
    awk -v key="$1:" '$1 == key { print $2; found = 1 } END { exit !found }' /proc/meminfo ||
        die "no $1 in /proc/meminfo"
}

human() { numfmt --from-unit=1024 --to=iec --round=nearest "$1"; }

while getopts ':i:c:l:m:s:p' opt; do
    case $opt in
        i) interval=$OPTARG ;;
        c) cpu_warn=$OPTARG ;;
        l) load_warn=$OPTARG ;;
        m) mem_warn=$OPTARG ;;
        s) swap_warn=$OPTARG ;;
        p) show_procs=1 ;;
        *) usage ;;
    esac
done
shift $(( OPTIND - 1 ))
(( $# == 0 )) || usage

for n in "$interval" "$cpu_warn" "$mem_warn" "$swap_warn"; do
    [[ $n =~ ^[0-9]{1,3}$ ]] || die "not a whole number from 0 to 999: '$n'"
done
[[ $load_warn =~ ^[0-9]{1,3}(\.[0-9]{1,2})?$ ]] || die "LOAD must look like 1 or 1.5: '$load_warn'"
interval=$((10#$interval)) cpu_warn=$((10#$cpu_warn))
mem_warn=$((10#$mem_warn)) swap_warn=$((10#$swap_warn))
(( interval >= 1 )) || die "SECONDS must be at least 1"

cpus=$(nproc) || die "nproc failed"

# --- CPU: two samples of /proc/stat, INTERVAL seconds apart
sample1=$(cpu_sample) || exit 3
sleep "$interval"
sample2=$(cpu_sample) || exit 3
read -r busy1 total1 <<< "$sample1"
read -r busy2 total2 <<< "$sample2"
(( total2 > total1 )) || die "CPU counters did not advance"
cpu_pct=$(( 100 * (busy2 - busy1) / (total2 - total1) ))
level=OK; (( cpu_pct >= cpu_warn )) && level=WARNING cpu_problem=1
report CPU "$level" "${cpu_pct}% busy over ${interval}s on $cpus CPUs (warn at ${cpu_warn}%)"

# --- Load: the 5-minute average, compared per CPU
read -r load1 load5 load15 _ < /proc/loadavg || die "cannot read /proc/loadavg"
per_cpu=$(( $(hundredths "$load5") / cpus ))              # in hundredths
level=OK; (( per_cpu >= $(hundredths "$load_warn") )) && level=WARNING cpu_problem=1
report LOAD "$level" "$load1 $load5 $load15 (5-min $(printf '%d.%02d' $((per_cpu / 100)) $((per_cpu % 100))) per CPU, warn at $load_warn)"

# --- Memory: MemAvailable is what new programs can get without swapping
mem_total=$(meminfo MemTotal) || exit 3
mem_avail=$(meminfo MemAvailable) || exit 3
mem_pct=$(( 100 * mem_avail / mem_total ))
level=OK; (( mem_pct < mem_warn )) && level=WARNING mem_problem=1
report MEMORY "$level" "$(human "$mem_avail") of $(human "$mem_total") available (${mem_pct}%, warn below ${mem_warn}%)"

# --- Swap: may not exist at all
swap_total=$(meminfo SwapTotal) || exit 3
if (( swap_total == 0 )); then
    report SWAP OK "none configured"
else
    swap_free=$(meminfo SwapFree) || exit 3
    swap_used=$(( swap_total - swap_free ))
    swap_pct=$(( 100 * swap_used / swap_total ))
    level=OK; (( swap_pct >= swap_warn )) && level=WARNING mem_problem=1
    report SWAP "$level" "$(human "$swap_used") of $(human "$swap_total") used (${swap_pct}%, warn at ${swap_warn}%)"
fi

if (( show_procs && cpu_problem )); then
    echo
    echo "Top processes by CPU (measured by top over 1 second):"
    top -b -n 2 -d 1 -o %CPU -w 512 |
        awk '/^ *PID /{ n++ } n == 2 { printf "%7s %-8s %5s %5s %s\n", $1, $2, $9, $10, $12 }' |
        head -n 4
fi
if (( show_procs && mem_problem )); then
    echo
    echo "Top processes by memory (resident set size in KiB):"
    ps -eo pid,user,rss,pmem,comm --sort=-rss | head -n 4
fi

exit "$status"

How It Works

  • Options and limits. Whole-number options are checked with a regular expression and read as decimal with 10#. The load limit may have up to two decimals (1.5), because load averages are decimal numbers.
  • Decimals without floating point. Bash arithmetic works only with integers. hundredths turns 1.5 into 150 and 0.63 into 63 by splitting at the dot and padding the fraction to two digits (frac=${frac}00, then the first two characters). The 5-minute load and the limit are both compared in hundredths, and printf '%d.%02d' turns the result back into a decimal for display. /proc/loadavg always prints two decimal places, so no precision is lost.
  • CPU. cpu_sample is called twice, INTERVAL seconds apart, exactly as in the earlier example. It runs inside $( ), a subshell, so the die inside it can only end that subshell; || exit 3 makes the main script stop too (lesson 125). A check that the totals actually increased prevents a division by zero.
  • Load. The 5-minute load is divided by the number of CPUs, so the same limit works on a 2-CPU laptop and a 64-CPU server.
  • Memory and swap. meminfo looks up one key with awk and returns a non-zero status when the key is missing (exit !found), for example MemAvailable on very old kernels. The memory check uses MemAvailable. Swap is checked only if it exists, which also avoids dividing by zero.
  • Result and exit status. report prints aligned lines and sets status to 1 on any warning. The script ends with 0 (OK) or 1 (WARNING), and with 3 (UNKNOWN) when it cannot do its job, following the same monitoring convention as disk-check.sh in lesson 166.
  • Finding the cause. With -p, a CPU or load warning lists the busiest processes and a memory or swap warning lists the largest ones. For CPU, the script does not use ps %CPU, which is an average over each process's whole lifetime (lesson 143). It runs top in batch mode for two updates one second apart (-b -n 2 -d 1), sorted by CPU (-o %CPU), with a wide line (-w 512) so command names are not cut. The first update has no earlier measurement to compare with, so awk counts the PID header lines and prints only the rows after the second one. For memory, ps --sort=-rss is accurate, because RSS is a current value.

Running the Complete Example

On an idle machine with 2 CPUs and no swap:

$ sysload-check.sh
CPU     OK       3% busy over 2s on 2 CPUs (warn at 90%)
LOAD    OK       0.67 0.63 0.27 (5-min 0.31 per CPU, warn at 1.0)
MEMORY  OK       7.2G of 7.8G available (91%, warn below 10%)
SWAP    OK       none configured
status 0

Three busy processes (yes > /dev/null) were started and left running for 75 seconds. A deliberately low load limit of 0.3 shows how both CPU checks react:

$ sysload-check.sh -l 0.3 -p
CPU     WARNING  100% busy over 2s on 2 CPUs (warn at 90%)
LOAD    WARNING  2.42 1.21 0.50 (5-min 0.60 per CPU, warn at 0.3)
MEMORY  OK       7.3G of 7.8G available (92%, warn below 10%)
SWAP    OK       none configured

Top processes by CPU (measured by top over 1 second):
    PID USER      %CPU  %MEM COMMAND
   1149 root      73.0   0.0 yes
   1148 root      70.0   0.0 yes
   1150 root      57.0   0.0 yes
status 1

Three processes share two CPUs, so together they use 200% in top's per-CPU terms and 100% of the machine. After 75 seconds the 1-minute load (2.42) is approaching 3, the number of tasks competing for the CPUs, while the 5-minute load (1.21) is still rising; this lag is why the script uses the 5-minute value for alerts.

Next, three Python processes each held 2 GB of memory. With the memory limit raised to 25%:

$ sysload-check.sh -i 1 -m 25 -p
CPU     OK       0% busy over 1s on 2 CPUs (warn at 90%)
LOAD    OK       0.94 0.68 0.27 (5-min 0.34 per CPU, warn at 1.0)
MEMORY  WARNING  1.7G of 7.8G available (21%, warn below 25%)
SWAP    OK       none configured

Top processes by memory (resident set size in KiB):
  PID USER       RSS %MEM COMMAND
 1081 root     1964148 23.9 python3
 1080 root     1964112 23.9 python3
 1082 root     1964104 23.9 python3
status 1

Only the memory list appears, because only a memory check failed. To test the swap branch, a 64 MB swap file was enabled and the memory processes were made larger; the start of that run (the process list that followed is not shown) was:

$ sysload-check.sh -i 1 -p
CPU     OK       0% busy over 1s on 2 CPUs (warn at 90%)
LOAD    OK       1.52 1.10 0.49 (5-min 0.55 per CPU, warn at 1.0)
MEMORY  OK       2.7G of 7.8G available (34%, warn below 10%)
SWAP    WARNING  60M of 64M used (93%, warn at 50%)

In that run the OOM killer had already ended one of the three processes, which is why available memory had recovered to 34% while swap was nearly full. Once the remaining processes finished, a new check still reported 12M of 64M used: the kernel does not bring pages back from swap until something needs them, so swap use can stay above zero long after memory pressure has passed.

Invalid options are reported with status 3:

$ sysload-check.sh extra
usage: sysload-check.sh [-i SECONDS] [-c CPU%] [-l LOAD] [-m MEM%] [-s SWAP%] [-p]
status 3
$ sysload-check.sh -c 101x
sysload-check.sh: not a whole number from 0 to 999: '101x'
status 3
$ sysload-check.sh -i 0
sysload-check.sh: SECONDS must be at least 1
status 3
$ sysload-check.sh -l 1.555
sysload-check.sh: LOAD must look like 1 or 1.5: '1.555'
status 3

A single run gives a snapshot. To see trends, schedule the script (lesson 170) every few minutes, append its output with a timestamp to a log (lesson 115), and alert only when the status is non-zero several times in a row, so that a short, harmless spike does not wake anyone up.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Monitoring CPU, Memory, and System Load and get answers drawn from it.

Signed-in readers only.