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 example | What it does |
|---|---|
MAX=95 | Sets the alert threshold in percent. |
EMAIL=server@127.0.0.1 | Sets the recipient. This is a placeholder and needs to be a real mailbox. |
grep 'cpu ' /proc/stat | Picks 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 ... $EMAIL | Sends the alert through the local mail system. |
Problems in the original script
- Decimal values break the comparison.
awkprints values such as3.84615. The[ ... -gt ... ]test only accepts integers, so Bash printsinteger expression expectedand no alert is ever sent. - It measures usage since boot. The counters in
/proc/statgrow 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,softirqandsteal. Busy time spent innice,irq,softirqandstealgoes 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$USEwould also produce a syntax error inside[ ]. - Mail needs setup.
mailis 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.1is 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/statreads only the first line, which is the aggregatecpuline, and splits it into named fields. Nogreporawkis needed.guestandguest_niceare left out of the total because the kernel already counts them insideuserandnice.iowaitis 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 theinteger expression expectederror.- 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
- Install a
mailclient. 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, thensudo systemctl enable --now postfix. - 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.
- Send a test message:
echo test | mail -s 'test' you@example.com. Check/var/log/mail.logorjournalctl -u postfixif it does not arrive. - Install the script:
sudo install -m 755 cpu_alert.sh /usr/local/bin/cpu_alert.sh. - Add a cron entry with
crontab -eso 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
| Command | Notes |
|---|---|
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/loadavg | Shows 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
| Symptom | Cause | Fix |
|---|---|---|
integer expression expected | A decimal value was passed to [ -gt ]. | Use integer arithmetic as in the corrected script, or strip decimals with ${var%.*}. |
mail: command not found | No mail client is installed. | Install mailutils (Debian/Ubuntu) or s-nail (RHEL family). |
| No error, but the email never arrives | There 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 load | The script uses one reading, which gives the average since boot. | Take two samples and use the difference. |
| It works by hand but not from cron | The 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,cpu1and other per-core lines. See Shell Scripting Tutorials: Function and looping with for and until. - Send the alert to a chat webhook with
curlinstead 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
- Shell Bash Scripting: Assignment & Excercise โ 3
- Shell Scripting Tutorials: Function
- Shell Bash Scripting Interview Questions and Answer โ Part 4
- More Shell Scripting tutorials
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.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals
nice info sir