Essential Bash Scripting Practices for Linux Operations and Monitoring
This guide presents practical Bash scripting techniques for Linux operations, covering script conventions, random string/number generation, colored output functions, batch user creation, package and service checks, host liveness testing, CPU/memory/disk monitoring, disk‑usage surveys across hosts, and website availability verification.
Precautions
1) Add interpreter line: #!/bin/bash 2) Use four spaces for indentation and add plenty of comments.
3) Naming conventions: uppercase for constants, lowercase for local variables, lowercase for functions, and names should reflect their purpose.
4) Variables are global by default; use local inside functions to avoid polluting other scopes.
5) Two commands help debugging: set -e to exit on non‑zero status, and set -x to print execution trace.
6) Always test scripts before deploying to production.
1. Generate Random String or Number
Random 8‑character string:
Random 8‑digit number:
cksum prints CRC checksum and byte count.
2. Define a Color Output Function
Use the function keyword to define a function, with or without the keyword.
3. Batch Create Users
4. Check If a Package Is Installed
5. Check Service Status
6. Check Host Liveness
Method 1: Put erroneous IPs into an array and consider a host down after three ping failures.
Method 2: Store failure count in a variable FAIL_COUNT and treat three consecutive failures as down.
Method 3: Use a for loop that breaks on a successful ping; otherwise print ping failure.
7. Monitor CPU, Memory, and Disk Utilization
CPU – use vmstat to analyze CPU statistics.
Memory – (image shows memory usage).
Disk – (image shows disk usage).
8. Batch Host Disk Utilization Monitoring
Prerequisite: password‑less SSH or key‑based login between monitoring and target hosts.
Create a configuration file that stores SSH connection info in the format: IP User Port.
9. Check Website Availability
1) Verify URL reachability.
2) Test URL three times; the logic mirrors the host‑liveness checks above.
These practical Bash script examples are frequently asked in interviews; hands‑on practice is essential for mastery.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
