Master Bash Scripting: Tips and Ready‑to‑Use Monitoring Scripts
This guide presents essential Bash scripting best practices and a collection of practical monitoring scripts—including random string generation, user creation, package checks, service status, host reachability, CPU/memory/disk usage, and website availability—complete with debugging tips and naming conventions for reliable automation.
Precautions
1) Add the interpreter line #!/bin/bash at the top of every script.
2) Use four spaces for indentation and add ample comments.
3) Naming convention: global variables in uppercase, local variables and functions in lowercase, and names should reflect their purpose.
4) Variables are global by default; declare local inside functions to avoid scope pollution.
5) Two useful debugging commands: set -e to exit on non‑zero status, and set -x to trace command execution.
6) Always test scripts thoroughly before deploying to production.
1. Generate Random Strings or Numbers
Random 8‑character string:
Random 8‑digit number:
Use cksum to print CRC checksum and byte count.
2. Define a Color‑Output Function
Use the function keyword (optional) to create a function that prints colored text.
3. Bulk Create Users
4. Check If a Package Is Installed
5. Verify Service Status
6. Check Host Liveness
Method 1: Store erroneous IPs in an array and consider the host down after three failed pings.
Method 2: Use a FAIL_COUNT variable to track consecutive failures.
Method 3: Loop with for; break on a successful ping, otherwise report failure after the loop.
7. Monitor CPU, Memory, and Disk Utilization
CPU: Use vmstat to analyze CPU statistics.
Memory:
Disk:
8. Bulk Host Disk Utilization Monitoring
Prerequisite: password‑less SSH (key‑based) between monitoring and target hosts.
Maintain a configuration file listing each host’s IP User Port information.
9. Verify Website Availability
1) Check URL reachability
2) Perform three consecutive checks – the logic mirrors the host‑liveness checks described earlier.
These Bash script examples are practical, frequently appear in technical interviews, and are intended for hands‑on practice rather than copy‑paste execution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
