MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Shell Bash Scripting: Assignment & Excercise – 4

This exercise asks for a Bash script that checks CPU usage and sends an email when it goes over a threshold. The script above reads /proc/stat, but it has two bugs: it compares a decimal number as if it were an integer, and it measures average usage since boot instead of current usage. Below you will find an explanation of the original, a corrected script that takes two samples, mail setup, cron scheduling, a way to test it, and ideas for extending the exercise.


Write a Shell Bash Script for report if CPU usage exceeds the threshold



How the example script works

The first line of /proc/stat starts with cpu and holds counters for all cores combined. Each counter is the time the CPU has spent in a given state since boot, measured in clock ticks. The columns are: cpu user nice system idle iowait irq softirq steal guest guest_nice. When awk reads that line, $2 is user, $3 is nice, $4 is system and $5 is idle.

Line in the exampleWhat it does
MAX=95Sets the alert threshold in percent.
EMAIL=server@127.0.0.1Sets the recipient. This is a placeholder and needs to be a real mailbox.
grep 'cpu ' /proc/statPicks the aggregate cpu line. The trailing space skips cpu0, cpu1 and the other per-core lines.
awk '{usage=($2+$4)*100/($2+$4+$5)} ...'Works out (user + system) / (user + system + idle) ร— 100.
if [ $USE -gt $MAX ]Compares the result with the threshold.
mail -s ... $EMAILSends the alert through the local mail system.

Problems in the original script

  • Decimal values break the comparison. awk prints values such as 3.84615. The [ ... -gt ... ] test only accepts integers, so Bash prints integer expression expected and no alert is ever sent.
  • It measures usage since boot. The counters in /proc/stat grow from the moment the machine starts. A single reading gives the average over the whole uptime. A server that has been mostly idle for a month will show a low number even while it is running at 100% right now. To get current usage, read the counters twice and compare the difference.
  • Some CPU states are left out. The formula ignores nice, iowait, irq, softirq and steal. Busy time spent in nice, irq, softirq and steal goes uncounted, so the result comes out too low.
  • There is no shebang and variables are unquoted. Without #!/usr/bin/env bash, the interpreter depends on how the script is started. An empty $USE would also produce a syntax error inside [ ].
  • Mail needs setup. mail is not installed by default on many distributions, and it needs a working mail transfer agent (MTA) or relay to deliver anything. Also, server@127.0.0.1 is not a deliverable address.

Corrected script

This version reads the counters twice, a few seconds apart, and uses only the difference between the readings. All maths is done with Bash integers, so the comparison always works. The threshold, interval and recipient can be overridden with environment variables.

#!/usr/bin/env bash
# cpu_alert.sh - email an alert when CPU usage exceeds a threshold
set -eu

THRESHOLD="${THRESHOLD:-95}"      # percent
INTERVAL="${INTERVAL:-5}"         # seconds between the two samples
EMAIL="${EMAIL:-ops@example.com}" # replace with a real mailbox
HOST="$(hostname)"

read_cpu() {
  # cpu user nice system idle iowait irq softirq steal guest guest_nice
  local cpu user nice system idle iowait irq softirq steal rest
  read -r cpu user nice system idle iowait irq softirq steal rest < /proc/stat
  IDLE=$(( idle + iowait ))
  TOTAL=$(( user + nice + system + idle + iowait + irq + softirq + steal ))
}

read_cpu; idle1=$IDLE; total1=$TOTAL
sleep "$INTERVAL"
read_cpu; idle2=$IDLE; total2=$TOTAL

dtotal=$(( total2 - total1 ))
didle=$(( idle2 - idle1 ))
if (( dtotal <= 0 )); then
  echo "Could not measure CPU usage" >&2
  exit 1
fi

# Integer percentage, rounded to the nearest whole number
usage=$(( (100 * (dtotal - didle) + dtotal / 2) / dtotal ))

echo "$(date '+%F %T') CPU usage: ${usage}% (threshold ${THRESHOLD}%)"

if (( usage > THRESHOLD )); then
  {
    echo "Host: $HOST"
    echo "CPU usage: ${usage}% over ${INTERVAL}s (threshold ${THRESHOLD}%)"
    echo
    echo "Top processes:"
    ps -eo pid,user,%cpu,comm --sort=-%cpu | head -n 6
  } | mail -s "CPU alert on $HOST: ${usage}%" "$EMAIL"
fiCode language: PHP (php)
  • read -r ... < /proc/stat reads only the first line, which is the aggregate cpu line, and splits it into named fields. No grep or awk is needed.
  • guest and guest_nice are left out of the total because the kernel already counts them inside user and nice.
  • iowait is counted as idle time. The CPU is not busy while it waits for disk I/O.
  • (( usage > THRESHOLD )) is an arithmetic comparison, so it never hits the integer expression expected error.
  • The email body lists the top five CPU consumers, so the person who gets the alert can start investigating right away.

Example output on a quiet machine:

$ ./cpu_alert.sh
2026-11-22 21:30:05 CPU usage: 7% (threshold 95%)

Install mail and schedule the check

  1. Install a mail client. On Debian or Ubuntu: sudo apt install mailutils. This pulls in Postfix and asks how to configure it. On RHEL, Rocky or Alma: sudo dnf install s-nail postfix, then sudo systemctl enable --now postfix.
  2. Configure the MTA to deliver to the internet or through your company's SMTP relay. Many cloud providers block outbound port 25, so a relay is often required.
  3. Send a test message: echo test | mail -s 'test' you@example.com. Check /var/log/mail.log or journalctl -u postfix if it does not arrive.
  4. Install the script: sudo install -m 755 cpu_alert.sh /usr/local/bin/cpu_alert.sh.
  5. Add a cron entry with crontab -e so the check runs every five minutes:
*/5 * * * * EMAIL=you@example.com /usr/local/bin/cpu_alert.sh >> /var/log/cpu_alert.log 2>&1Code language: JavaScript (javascript)

Note: Cron runs jobs with a minimal environment and a short PATH. Use full paths and set variables such as EMAIL in the crontab line or inside the script. Also make sure the user that runs the job can write to the log file.

Test the alert

There is no need to wait for a real incident. Run one yes process per core to load the CPU, run the check with a lower threshold, then stop the load:

# start one busy loop per CPU core
for i in $(seq "$(nproc)"); do yes > /dev/null & done

# run the check with a lower threshold
THRESHOLD=50 EMAIL=you@example.com ./cpu_alert.sh

# stop the load
kill $(jobs -p)Code language: PHP (php)

The script should report a value close to 100% and send an email. If stress-ng is installed, stress-ng --cpu 0 --timeout 60s does the same job and stops on its own after 60 seconds.

Other ways to read CPU usage

CommandNotes
vmstat 1 2 | tail -n 1 | awk '{print 100 - $15}'vmstat comes from procps and is usually installed. The second line covers the last second, and column 15 is id (idle).
LC_ALL=C mpstat 1 1 | awk '/^Average/ {print 100 - $NF}'Needs the sysstat package. The last column is %idle. Setting LC_ALL=C keeps the Average label in English.
uptime or cat /proc/loadavgShows load average, which is not the same as CPU percentage. Load also counts tasks waiting on I/O. Compare it with nproc.

Note: mpstat prints decimal values. Strip the decimal part with usage=${usage%.*} before an integer comparison, or do the comparison in awk.

Common errors and fixes

SymptomCauseFix
integer expression expectedA decimal value was passed to [ -gt ].Use integer arithmetic as in the corrected script, or strip decimals with ${var%.*}.
mail: command not foundNo mail client is installed.Install mailutils (Debian/Ubuntu) or s-nail (RHEL family).
No error, but the email never arrivesThere is no MTA, the relay is wrong, or outbound port 25 is blocked.Check the mail logs and configure an SMTP relay.
The value is always low, even under loadThe script uses one reading, which gives the average since boot.Take two samples and use the difference.
It works by hand but not from cronThe script is not executable, has a relative path, or is missing environment variables.Use chmod +x, absolute paths, and set variables in the crontab.

Extend the exercise

  • Alert only after three breaches in a row, by storing a counter in a file under /var/tmp. This filters out short spikes.
  • Add a cooldown so the same host does not send an email every five minutes during a long incident.
  • Write every reading to syslog with logger -t cpu_alert "CPU ${usage}%".
  • Move the sampling into a function and loop over the cpu0, cpu1 and other per-core lines. See Shell Scripting Tutorials: Function and looping with for and until.
  • Send the alert to a chat webhook with curl instead of email. For production systems, a monitoring stack such as Prometheus with node_exporter is more reliable than a cron script.

Frequently asked questions

How do I get current CPU usage in a Bash script?

Read the first line of /proc/stat twice, a few seconds apart. Then compute 100 ร— (change in total โˆ’ change in idle) / change in total. Alternatives are vmstat 1 2 or mpstat 1 1 from sysstat.

Why does Bash say integer expression expected?

The -gt, -lt and -eq tests in [ ] only accept whole numbers. A value like 12.5 causes this error, so round the value, strip the decimals with ${var%.*}, or compare in awk.

Why doesn't the mail command send anything?

mail only hands the message to a local mail transfer agent such as Postfix. If no MTA is configured, or outbound SMTP is blocked, the message never leaves the server. Check the mail logs and set up a relay.

Is load average the same as CPU usage?

No. Load average is the number of runnable tasks, plus tasks in uninterruptible I/O wait, averaged over 1, 5 and 15 minutes. CPU usage is the percentage of time the CPUs were busy. A load equal to the core count roughly means the CPUs are fully used.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Shell Bash Scripting: Assignment & Excercise โ€“ 16

This exercise asks for a Bash script that packs a file or directory into a compressed tar archive and then encrypts it with a passphrase. The solution…

Read More

Shell Bash Scripting: Assignment & Excercise โ€“ 15

This exercise builds a Bash script that takes an IP address, sends it to the free ip-api.com geolocation API with curl, and uses jq to print the…

Read More

Shell script to git add and commit and push each directory at a time

This page shows how to use a Bash script to stage, commit and push changes one directory at a time. That can mean a folder full of…

Read More

AWS Tutorials: AWS CodeBuild – Buildspec code for creating AMI from running instances

This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged environment=uat and creates an AMI from each one with the AWS CLI. It…

Read More

Shell Bash Scripting: Assignment & Excercise – 7

This exercise uses Bash, rsync and SSH to copy a local file to a remote backup server, then sends an email when the copy finishes. Below the…

Read More

Shell Scripting Tutorials: Function

A Bash function is a named block of commands that takes arguments as $1, $2, … and $@, and hands results back through its output or its…

Read More
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Suraj Rampure
Suraj Rampure
3 years ago

nice info sir

1
0
Would love your thoughts, please comment.x
()
x