{"id":2350,"date":"2026-11-22T22:09:22","date_gmt":"2026-11-22T22:09:22","guid":{"rendered":"http:\/\/www.scmgalaxy.com\/tutorials\/?p=2350"},"modified":"2026-11-22T22:09:22","modified_gmt":"2026-11-22T22:09:22","slug":"test-your-shell-scripting-skills-program-9","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/test-your-shell-scripting-skills-program-9\/","title":{"rendered":"Shell Bash Scripting: Assignment &#038; Excercise &#8211; 4"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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 <code>\/proc\/stat<\/code>, 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.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Write a Shell Bash Script for report if CPU usage exceeds the threshold<\/h2>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/2514d0b1d14103f9701bd1d0f71e0a9f.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How the example script works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The first line of <code>\/proc\/stat<\/code> starts with <code>cpu<\/code> 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: <code>cpu user nice system idle iowait irq softirq steal guest guest_nice<\/code>. When <code>awk<\/code> reads that line, <code>$2<\/code> is user, <code>$3<\/code> is nice, <code>$4<\/code> is system and <code>$5<\/code> is idle.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Line in the example<\/th><th>What it does<\/th><\/tr><\/thead><tbody><tr><td><code>MAX=95<\/code><\/td><td>Sets the alert threshold in percent.<\/td><\/tr><tr><td><code>EMAIL=server@127.0.0.1<\/code><\/td><td>Sets the recipient. This is a placeholder and needs to be a real mailbox.<\/td><\/tr><tr><td><code>grep &#039;cpu &#039; \/proc\/stat<\/code><\/td><td>Picks the aggregate <code>cpu<\/code> line. The trailing space skips <code>cpu0<\/code>, <code>cpu1<\/code> and the other per-core lines.<\/td><\/tr><tr><td><code>awk &#039;{usage=($2+$4)*100\/($2+$4+$5)} ...&#039;<\/code><\/td><td>Works out (user + system) \/ (user + system + idle) \u00d7 100.<\/td><\/tr><tr><td><code>if [ $USE -gt $MAX ]<\/code><\/td><td>Compares the result with the threshold.<\/td><\/tr><tr><td><code>mail -s ... $EMAIL<\/code><\/td><td>Sends the alert through the local mail system.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Problems in the original script<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Decimal values break the comparison.<\/strong> <code>awk<\/code> prints values such as <code>3.84615<\/code>. The <code>[ ... -gt ... ]<\/code> test only accepts integers, so Bash prints <code>integer expression expected<\/code> and no alert is ever sent.<\/li>\n\n\n<li><strong>It measures usage since boot.<\/strong> The counters in <code>\/proc\/stat<\/code> 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.<\/li>\n\n\n<li><strong>Some CPU states are left out.<\/strong> The formula ignores <code>nice<\/code>, <code>iowait<\/code>, <code>irq<\/code>, <code>softirq<\/code> and <code>steal<\/code>. Busy time spent in <code>nice<\/code>, <code>irq<\/code>, <code>softirq<\/code> and <code>steal<\/code> goes uncounted, so the result comes out too low.<\/li>\n\n\n<li><strong>There is no shebang and variables are unquoted.<\/strong> Without <code>#!\/usr\/bin\/env bash<\/code>, the interpreter depends on how the script is started. An empty <code>$USE<\/code> would also produce a syntax error inside <code>[ ]<\/code>.<\/li>\n\n\n<li><strong>Mail needs setup.<\/strong> <code>mail<\/code> is not installed by default on many distributions, and it needs a working mail transfer agent (MTA) or relay to deliver anything. Also, <code>server@127.0.0.1<\/code> is not a deliverable address.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Corrected script<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">#!\/usr\/bin\/env bash<\/span>\n<span class=\"hljs-comment\"># cpu_alert.sh - email an alert when CPU usage exceeds a threshold<\/span>\nset -eu\n\nTHRESHOLD=<span class=\"hljs-string\">\"${THRESHOLD:-95}\"<\/span>      <span class=\"hljs-comment\"># percent<\/span>\nINTERVAL=<span class=\"hljs-string\">\"${INTERVAL:-5}\"<\/span>         <span class=\"hljs-comment\"># seconds between the two samples<\/span>\nEMAIL=<span class=\"hljs-string\">\"${EMAIL:-ops@example.com}\"<\/span> <span class=\"hljs-comment\"># replace with a real mailbox<\/span>\nHOST=<span class=\"hljs-string\">\"$(hostname)\"<\/span>\n\nread_cpu() {\n  <span class=\"hljs-comment\"># cpu user nice system idle iowait irq softirq steal guest guest_nice<\/span>\n  local cpu user nice system idle iowait irq softirq steal rest\n  read -r cpu user nice system idle iowait irq softirq steal rest &lt; \/proc\/stat\n  IDLE=$(( idle + iowait ))\n  TOTAL=$(( user + nice + system + idle + iowait + irq + softirq + steal ))\n}\n\nread_cpu; idle1=$IDLE; total1=$TOTAL\nsleep <span class=\"hljs-string\">\"$INTERVAL\"<\/span>\nread_cpu; idle2=$IDLE; total2=$TOTAL\n\ndtotal=$(( total2 - total1 ))\ndidle=$(( idle2 - idle1 ))\n<span class=\"hljs-keyword\">if<\/span> (( dtotal &lt;= <span class=\"hljs-number\">0<\/span> )); then\n  <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Could not measure CPU usage\"<\/span> &gt;&amp;<span class=\"hljs-number\">2<\/span>\n  <span class=\"hljs-keyword\">exit<\/span> <span class=\"hljs-number\">1<\/span>\nfi\n\n<span class=\"hljs-comment\"># Integer percentage, rounded to the nearest whole number<\/span>\nusage=$(( (<span class=\"hljs-number\">100<\/span> * (dtotal - didle) + dtotal \/ <span class=\"hljs-number\">2<\/span>) \/ dtotal ))\n\n<span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"$(date '+%F %T') CPU usage: ${usage}% (threshold ${THRESHOLD}%)\"<\/span>\n\n<span class=\"hljs-keyword\">if<\/span> (( usage &gt; THRESHOLD )); then\n  {\n    <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Host: $HOST\"<\/span>\n    <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"CPU usage: ${usage}% over ${INTERVAL}s (threshold ${THRESHOLD}%)\"<\/span>\n    <span class=\"hljs-keyword\">echo<\/span>\n    <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Top processes:\"<\/span>\n    ps -eo pid,user,%cpu,comm --sort=-%cpu | head -n <span class=\"hljs-number\">6<\/span>\n  } | mail -s <span class=\"hljs-string\">\"CPU alert on $HOST: ${usage}%\"<\/span> <span class=\"hljs-string\">\"$EMAIL\"<\/span>\nfi<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><code>read -r ... &lt; \/proc\/stat<\/code> reads only the first line, which is the aggregate <code>cpu<\/code> line, and splits it into named fields. No <code>grep<\/code> or <code>awk<\/code> is needed.<\/li>\n\n\n<li><code>guest<\/code> and <code>guest_nice<\/code> are left out of the total because the kernel already counts them inside <code>user<\/code> and <code>nice<\/code>.<\/li>\n\n\n<li><code>iowait<\/code> is counted as idle time. The CPU is not busy while it waits for disk I\/O.<\/li>\n\n\n<li><code>(( usage &gt; THRESHOLD ))<\/code> is an arithmetic comparison, so it never hits the <code>integer expression expected<\/code> error.<\/li>\n\n\n<li>The email body lists the top five CPU consumers, so the person who gets the alert can start investigating right away.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Example output on a quiet machine:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">$ .\/cpu_alert.sh\n2026-11-22 21:30:05 CPU usage: 7% (threshold 95%)<\/code><\/span><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Install mail and schedule the check<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Install a <code>mail<\/code> client. On Debian or Ubuntu: <code>sudo apt install mailutils<\/code>. This pulls in Postfix and asks how to configure it. On RHEL, Rocky or Alma: <code>sudo dnf install s-nail postfix<\/code>, then <code>sudo systemctl enable --now postfix<\/code>.<\/li>\n\n\n<li>Configure the MTA to deliver to the internet or through your company&#039;s SMTP relay. Many cloud providers block outbound port 25, so a relay is often required.<\/li>\n\n\n<li>Send a test message: <code>echo test | mail -s &#039;test&#039; you@example.com<\/code>. Check <code>\/var\/log\/mail.log<\/code> or <code>journalctl -u postfix<\/code> if it does not arrive.<\/li>\n\n\n<li>Install the script: <code>sudo install -m 755 cpu_alert.sh \/usr\/local\/bin\/cpu_alert.sh<\/code>.<\/li>\n\n\n<li>Add a cron entry with <code>crontab -e<\/code> so the check runs every five minutes:<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">*<span class=\"hljs-regexp\">\/5 * * * * EMAIL=you@example.com \/u<\/span>sr\/local\/bin\/cpu_alert.sh &gt;&gt; <span class=\"hljs-regexp\">\/var\/<\/span>log\/cpu_alert.log <span class=\"hljs-number\">2<\/span>&gt;&amp;<span class=\"hljs-number\">1<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Cron runs jobs with a minimal environment and a short <code>PATH<\/code>. Use full paths and set variables such as <code>EMAIL<\/code> in the crontab line or inside the script. Also make sure the user that runs the job can write to the log file.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Test the alert<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">There is no need to wait for a real incident. Run one <code>yes<\/code> process per core to load the CPU, run the check with a lower threshold, then stop the load:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># start one busy loop per CPU core<\/span>\n<span class=\"hljs-keyword\">for<\/span> i in $(seq <span class=\"hljs-string\">\"$(nproc)\"<\/span>); <span class=\"hljs-keyword\">do<\/span> yes &gt; \/dev\/<span class=\"hljs-keyword\">null<\/span> &amp; done\n\n<span class=\"hljs-comment\"># run the check with a lower threshold<\/span>\nTHRESHOLD=<span class=\"hljs-number\">50<\/span> EMAIL=you@example.com .\/cpu_alert.sh\n\n<span class=\"hljs-comment\"># stop the load<\/span>\nkill $(jobs -p)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The script should report a value close to 100% and send an email. If <code>stress-ng<\/code> is installed, <code>stress-ng --cpu 0 --timeout 60s<\/code> does the same job and stops on its own after 60 seconds.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Other ways to read CPU usage<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Command<\/th><th>Notes<\/th><\/tr><\/thead><tbody><tr><td><code>vmstat 1 2 | tail -n 1 | awk &#039;{print 100 - $15}&#039;<\/code><\/td><td><code>vmstat<\/code> comes from procps and is usually installed. The second line covers the last second, and column 15 is <code>id<\/code> (idle).<\/td><\/tr><tr><td><code>LC_ALL=C mpstat 1 1 | awk &#039;\/^Average\/ {print 100 - $NF}&#039;<\/code><\/td><td>Needs the <code>sysstat<\/code> package. The last column is <code>%idle<\/code>. Setting <code>LC_ALL=C<\/code> keeps the <code>Average<\/code> label in English.<\/td><\/tr><tr><td><code>uptime<\/code> or <code>cat \/proc\/loadavg<\/code><\/td><td>Shows load average, which is not the same as CPU percentage. Load also counts tasks waiting on I\/O. Compare it with <code>nproc<\/code>.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> <code>mpstat<\/code> prints decimal values. Strip the decimal part with <code>usage=${usage%.*}<\/code> before an integer comparison, or do the comparison in <code>awk<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>integer expression expected<\/code><\/td><td>A decimal value was passed to <code>[ -gt ]<\/code>.<\/td><td>Use integer arithmetic as in the corrected script, or strip decimals with <code>${var%.*}<\/code>.<\/td><\/tr><tr><td><code>mail: command not found<\/code><\/td><td>No mail client is installed.<\/td><td>Install <code>mailutils<\/code> (Debian\/Ubuntu) or <code>s-nail<\/code> (RHEL family).<\/td><\/tr><tr><td>No error, but the email never arrives<\/td><td>There is no MTA, the relay is wrong, or outbound port 25 is blocked.<\/td><td>Check the mail logs and configure an SMTP relay.<\/td><\/tr><tr><td>The value is always low, even under load<\/td><td>The script uses one reading, which gives the average since boot.<\/td><td>Take two samples and use the difference.<\/td><\/tr><tr><td>It works by hand but not from cron<\/td><td>The script is not executable, has a relative path, or is missing environment variables.<\/td><td>Use <code>chmod +x<\/code>, absolute paths, and set variables in the crontab.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Extend the exercise<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Alert only after three breaches in a row, by storing a counter in a file under <code>\/var\/tmp<\/code>. This filters out short spikes.<\/li>\n\n\n<li>Add a cooldown so the same host does not send an email every five minutes during a long incident.<\/li>\n\n\n<li>Write every reading to syslog with <code>logger -t cpu_alert &quot;CPU ${usage}%&quot;<\/code>.<\/li>\n\n\n<li>Move the sampling into a function and loop over the <code>cpu0<\/code>, <code>cpu1<\/code> and other per-core lines. See <a href=\"https:\/\/www.devopsschool.com\/blog\/shell-scripting-tutorials-function\/\">Shell Scripting Tutorials: Function<\/a> and <a href=\"https:\/\/www.devopsschool.com\/blog\/shell-scripting-tutorials-looping-iteration-statatement-using-for-until\/\">looping with for and until<\/a>.<\/li>\n\n\n<li>Send the alert to a chat webhook with <code>curl<\/code> instead of email. For production systems, a monitoring stack such as Prometheus with node_exporter is more reliable than a cron script.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">How do I get current CPU usage in a Bash script?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Read the first line of \/proc\/stat twice, a few seconds apart. Then compute 100 \u00d7 (change in total \u2212 change in idle) \/ change in total. Alternatives are <code>vmstat 1 2<\/code> or <code>mpstat 1 1<\/code> from sysstat.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why does Bash say integer expression expected?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>-gt<\/code>, <code>-lt<\/code> and <code>-eq<\/code> tests in <code>[ ]<\/code> only accept whole numbers. A value like 12.5 causes this error, so round the value, strip the decimals with <code>${var%.*}<\/code>, or compare in awk.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why doesn&#039;t the mail command send anything?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>mail<\/code> 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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is load average the same as CPU usage?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/test-your-shell-scripting-skills-program-4\/\">Shell Bash Scripting: Assignment &amp; Excercise \u2013 3<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/shell-scripting-tutorials-function\/\">Shell Scripting Tutorials: Function<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-50-interview-question-and-answers-of-bash-scripting\/\">Shell Bash Scripting Interview Questions and Answer \u2013 Part 4<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/programming\/shell-script\/\">More Shell Scripting tutorials<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[454],"tags":[137],"class_list":["post-2350","post","type-post","status-publish","format-standard","hentry","category-shell-script","tag-bash"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/2350","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=2350"}],"version-history":[{"count":4,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/2350\/revisions"}],"predecessor-version":[{"id":80115,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/2350\/revisions\/80115"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=2350"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=2350"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=2350"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}