r/linuxadmin • u/CautiousCat3294 • Nov 24 '25
Lightweight CPU Monitoring Script for Linux admins (Bash-based, alerts + logging)
Created a lightweight CPU usage monitor for small setups. Uses top/awk for parsing and logs spikes.
Full breakdown: https://youtu.be/nVU1JIWGnmI
I am open to any suggestion that will improve this script
0
Upvotes
10
u/biffbobfred Nov 25 '25
This will sound harsher than intended but I’m too tired to worry about tone: I’m not watching a YouTube vid on a script. It’s shell you can post it I can read it.
1
u/whetu Nov 26 '25
You're re-inventing a wheel, something like prometheus exporter would be infinitely better. However, this is still a good exercise for learning shell scripting.
Ok, let's get straight to the code:
https://github.com/Abhilashchauhan1994/bash_scripts/blob/main/cpu_usage.sh
First thing: don't use extensions. Ref 1, Ref 2
Next: Don't use UPPERCASE blindly unless you know when and why you should. This is a de-facto namespace used for shell-special variables like
$RANDOMand global variables like$PATH, so when you use UPPERCASE, you risk clobbering an existing variable. In other languages this is known as "don't clobber the global scope".And just to drive this home, you have proven this exact point with this line:
On many systems,
HOSTNAMEis already present. You just clobbered an environment variable.Is better.
Then falls back to making an external call.
Moving on:
This is on the cusp of goodness. Most systems should have
top,awkandmailx(of the three this one is most likely to be missing), so it's not so big a deal in this immediate script. But the problem with this approach is that when you use it in a larger script, and it turns out you have multiple missing commands. Here's the experience:Instead, build an array of missing commands and act on the size of that array, something like this:
(That's intentionally terse.)
By moving the desired commands out of this function, it is now genericised and available for re-use in other scripts. You can then call it with your list of required commands:
Next
Instead of parsing the output of
top, consider parsing the first line of/proc/statinstead.Prefer
printfoverechofor portability, sanity and because the POSIX spec forechosays so.Prefer declaring vars as local and then defining them separately.
This is not a reliable "is this an integer?" test:
It's definitely not a portable one either. Here's a function from my toolchest:
Now you have:
I'm sure there's more, but that's already a lot for you to go away and work with.