Guides
How to Write a Bash Script for Server Health and Disk Alerts By Ravindra Bagale , DevOps trainer · LinkedIn · Published: 28 October 2026 · Last updated: 28 October 2026
Write a Bash health script that checks CPU, memory and disk, prints a report, and can alert — the junior task Capgemini and Wipro-style teams still assign.
English मराठी हिंदी
Friends, a health script is your first automation badge. Chala mitrano — alert only when thresholds break.
मित्रांनो, health script ही पहिली automation badge. Chala mitrano — threshold मोडल्यावरच alert.
मित्रों, health script पहली automation badge है। Chala mitrano — threshold टूटने पर ही alert।
Quick answer
Hold this vertical picture:
Safe skeleton with set -euo pipefail.
Collect from /proc and df.
Thresholds + exit codes.
Cron with absolute paths.
No real secrets in files.
Language: English · मराठी · हिंदी
Collect metrics CPU mem disk
Compare thresholds e.g. disk 90%
Write report file or stdout
Optional alert mail or webhook
Health script flow
Why write a health script
Waiting for users in Mumbai or Frankfurt to report a full disk is too late. A five-minute Bash check is the first DevOps automation many teams trust.
Why: Catch pressure before outage.
What: Bash script: metrics, thresholds, report, optional alert.
How: Build pieces below on Amazon Linux or Ubuntu.
Concept 1: Safe script skeleton
Why: Broken scripts with set +u catch mistakes early.
What: shebang, set -euo pipefail, chmod 700.
How: Start every ops script this way.
Example 1: Shebang and safe mode
Type this:
printf '%s\n' '#!/usr/bin/env bash' 'set -euo pipefail' > /tmp/health.sh
head -2 /tmp/health.sh
You will see:
#!/usr/bin/env bash
set -euo pipefail
What it means: set -euo pipefail stops on errors and unset vars.
Example 2: Disk percent function
Type this:
python3 -c "u=91; print('ALERT' if u>=90 else 'ok')"
You will see:
What it means: Threshold logic before any webhook.
Example 3: chmod private
Type this:
chmod 700 /tmp/health.sh
stat -c %a /tmp/health.sh 2 >/dev/null || stat -f %A /tmp/health.sh
You will see:
What it means: Never world-writable scripts.
Concept 2: Collect CPU memory disk
Why: You cannot alert on vibes.
What: /proc/stat, /proc/meminfo, df -P.
How: Parse stable columns.
Example 4: CPU from /proc
Type this:
grep '^cpu ' /proc/stat | awk '{print \$2}'
You will see:
What it means: /proc/stat feeds CPU math on Linux.
Example 5: Memory available
Type this:
awk '/MemAvailable/ {print \$2}' /proc/meminfo
You will see:
What it means: Values are kB. Convert for humans.
Example 6: Disk use awk
Type this:
df -P / | awk 'NR==2 {print \$5}'
You will see:
What it means: Use df -P for stable columns.
Concept 3: Report and exit codes
Why: Cron and monitoring read exit codes.
What: Write a report file; exit 0/2.
How: Dry-run webhooks with fake URLs.
Example 7: Report file
Type this:
printf '%s\n' 'host=lab' 'disk=39%' 'mem_ok=yes' > /tmp/health-report.txt
cat /tmp/health-report.txt
You will see:
host=lab
disk=39%
mem_ok=yes
What it means: Reports beat silent scripts.
Example 8: Exit codes
Type this:
python3 -c "import sys; sys.exit(2)" ; echo exit = \$ ?
You will see:
What it means: Non-zero exits drive cron alerts.
Example 9: Webhook dry-run
Type this:
printf '%s\n' 'POST https://hooks.example.invalid/alert' 'body={text: disk 91%}'
You will see:
POST https://hooks.example.invalid/alert
body={text: disk 91%}
What it means: Use a fake URL in labs; never commit real secrets.
Concept 4: Schedule and harden
Why: A script that never runs helps nobody.
What: cron every 5 minutes; absolute paths.
How: Log redirects; bash -n first.
Example 10: Cron line draft
Type this:
printf '%s\n' '*/5 * * * * /home/ec2-user/bin/health.sh >> /var/log/health.log 2>&1'
You will see:
*/5 * * * * /home/ec2-user/bin/health.sh >> /var/log/health.log 2>&1
What it means: Redirect stdout and stderr.
Example 11: PATH reminder
Type this:
printf '%s\n' 'Use absolute paths in cron' '/usr/bin/df not df'
You will see:
Use absolute paths in cron
/usr/bin/df not df
What it means: Cron has a tiny PATH.
Example 12: Test once
Type this:
bash -n /tmp/health.sh && echo SYNTAX_OK
You will see:
What it means: bash -n checks syntax without running.
Minimal script shape
shebang + set -euo pipefail
read disk percent
if >= 90 then exit 2 and message
else write OK report
cron with >> log 2>&1
Suppose: Hyderabad e-commerce box
Disk hits 92 percent before Big Billion days. Script pages Slack-style webhook.
Suppose: Berlin SaaS VM
Memory Available drops. Same script pattern, different threshold.
Ravindra Bagale's Tip
English मराठी हिंदी
At Capgemini and Wipro accounts, juniors are asked to script disk alerts before fancy tools. Keep scripts private (mode 700) and never store real webhook secrets in git.
Capgemini/Wipro style खात्यांवर juniors ना disk alerts script करायला सांगतात. Scripts private (700) ठेवा; खरे webhook secrets git मध्ये ठेवू नका.
Capgemini/Wipro style खातों पर juniors से disk alerts script करवाते हैं। Scripts private (700) रखें; असली webhook secrets git में न रखें।
Check yourself (quiz)
Q1. Why set -euo pipefail? Fail on error, unset vars and pipe failures.
Q2. Safe file mode for scripts? 700 — owner only.
Q3. Where is MemAvailable? /proc/meminfo on Linux.
Q4. Why absolute paths in cron? Cron PATH is minimal.
Q5. Fake webhook in labs? Yes — never commit real secrets.
Reading tracking
Mark this guide when you finish. Your browser remembers it on this device.
Mark as read
Skeleton → metrics → thresholds → report → cron. Mode 700. No secrets.
Did you understand? Let us try it once more.
Live batch madhe shikaycha aahe? Online / offline training with Ravindra Bagale – AWS, DevOps, Data Analytics, Power BI, Cyber Security.
Enquire now → Chat on WhatsApp
Frequently asked questions Why set -euo pipefail? Fail on error, unset variables and pipe failures.
Safe mode for scripts? 700 — owner only.
Where is MemAvailable? /proc/meminfo on Linux.
Why absolute paths in cron? Cron has a minimal PATH.
Should labs use real webhooks? No — use fake URLs; never commit secrets.
What exit code for alert? Non-zero such as 2 for threshold breach.
How to Install Nginx on Amazon Linux 2023 (EC2) How to SSH into EC2 from Windows, Mac and Linux How to Launch an EC2 Instance in AWS (Step by Step) How to Install Apache (httpd) on Amazon Linux 2023 EC2 How to Fix Permission denied (publickey) on AWS EC2 How to Open Port 80 and 443 in an EC2 Security Group How to Attach an Elastic IP to an EC2 Instance How to Host a Static Website on EC2 with Nginx How to Connect a GoDaddy Domain to AWS EC2 How to Install a Free SSL Certificate on EC2 (Certbot) How to Install WordPress on AWS EC2 (Amazon Linux 2023) How to Increase EBS Volume Size Without Downtime How to Attach an IAM Role to an EC2 Instance How to Install Docker on Amazon Linux 2023 (EC2) How to Install and Configure AWS CLI (Windows, Mac, Linux) How to Set Up an AWS Billing Alarm and Budget (Free Tier) How to Host a Static Website on Amazon S3 How to Create an IAM User with MFA (Stop Using Root) How to Set Up an Application Load Balancer for Two EC2s How to Create an RDS MySQL Database and Connect from EC2 Your First AWS Lambda Function in Python (Console) How to Install WordPress Plugins and Themes Without FTP Nginx Config Explained: Change Port, Root and Index (AL2023) How to Create a Custom VPC in AWS: Subnets, IGW and Routes AWS VPC CIDR and Subnet Calculation Explained Public vs Private Subnet in AWS: The Route Table Difference How to Block an IP Address or IP Range Using AWS NACL Security Group vs NACL in AWS: Differences with Examples How to Set Up a NAT Gateway for a Private Subnet in AWS How to SSH into a Private EC2 Through a Bastion (Jump) Host 3-Tier Architecture on AWS: Nginx, PHP and MySQL in a VPC What Is Phishing and How to Spot It What Is Ransomware and How to Protect Yourself How to Enable MFA on Google, Microsoft and AWS OWASP Top 10 Explained Simply (2025) What Is SQL Injection and How to Prevent It How to Set Up SPF, DKIM and DMARC for Email How to Harden a Linux Server (Checklist) How to Use Nmap for Basic Network Scanning (Ethical Lab) How to Analyse a Phishing Email Like a SOC Analyst Incident Response Plan for Beginners (First 24 Hours) What Is Malware? Types and How to Protect Yourself How to Set Up a Password Manager (Beginner Guide) EDR vs Antivirus: What’s the Difference What Is SIEM? How SOC Analysts Use It What Is a Data Breach? What to Do If Your Data Was Exposed How Does a Firewall Work? (Beginner Explainer) What Is a VPN and When Should You Use One? Zero Trust Security Explained Simply What Is XSS (Cross-Site Scripting) and How to Prevent It How to Secure Your Home Wi‑Fi Network (Step-by-Step) Vulnerability Management: CVEs, KEV, Patching and Verification Windows Event Logs and Sysmon for Beginner SOC MITRE ATT&CK + Your First Sigma Detection Rule (Defence) Cloud IAM Least Privilege AI Security: Defend Prompt Injection and Data Leakage SBOM, Dependency Risk and Secret Leaks Wireshark Packet Analysis for Beginners (Defender View) Backup and Disaster Recovery: RPO, RTO and Restore Testing Cryptography, TLS, Certificates and PKI in Practice Safe Metasploitable / Vulnerable Home Lab Setup What Is Penetration Testing? (Ethical, Authorised Only) Secure REST APIs with OWASP API Security Top 10 Threat Hunting for Beginners (Defence) Kubernetes Security Basics for Defenders DevSecOps Security Pipeline (SAST, SCA, Secrets) Python for SOC Analysts (Defence Automation) Active Directory Hardening and Monitoring (Defender Guide) Machine Identity Security: Service Accounts, Keys and Workloads STRIDE Threat Modeling Guide for Builders and Defenders Digital Forensics for Beginners: Evidence, Hashes and Timelines OT / ICS Cybersecurity Monitoring Lab (Safe Education) What Is Cloud Security? Beginner’s Guide AWS Security Best Practices Checklist What Is a SOC? What Does a SOC Analyst Do? How to Write a Cybersecurity Incident Report Azure Cloud Security Basics for Beginners Cybersecurity Skills Companies Hire For (2026) 50 Cybersecurity Interview Questions and Answers (Basics) 50 SOC Analyst Interview Questions and Answers 50 Network Security Interview Questions and Answers 50 Cloud / AWS Security Interview Questions and Answers 50 IAM, MFA and Zero Trust Interview Questions and Answers AppSec OWASP Interview Questions (50) — SQLi, XSS, API Linux Security Interview Questions (50) — Hardening & Commands Incident Response Interview Questions (50) — IR / DFIR Beginner Ethical Hacking & Pentest Interview Questions (50) — Concepts Python Scripting for SOC Interview Questions (50) How Android Phone Hacking Happens (Defence Guide) Android Device Cloning Risks and Defence How Android Data Theft Happens — and How to Defend Android Safe App Install and Sideload Risks Android Malware and Spyware: Signs, Remove and Protect Android Banking OTP, SIM Swap and MFA Protection Lost or Stolen Android: Find, Lock and Remote Wipe Android Public Wi‑Fi and Hotspot Risks How iPhone Hacking Happens (Defence Guide) Apple ID and iCloud Takeover Defence iPhone Data Theft Risks and Defence iPhone App, Profile and MDM Risks Stolen or Lost iPhone: Find My and Lockdown Mode iPhone Banking OTP, SIM Swap and MFA Protection Signs Your iPhone May Be Compromised How Windows Laptop Hacking Happens (Defence Guide) Windows Malware and Ransomware Protection Windows Safe Software Install Habits Windows Update and Microsoft Defender Basics Windows Account, MFA and BitLocker Hardening Windows Remote Access: RDP and AnyDesk Risks Windows Data Theft: Browser and USB Defence Windows Laptop Stolen or Infected: Recover Checklist Power BI Desktop vs Service vs Mobile Explained Install Power BI Desktop and Build Your First Report Connect Excel and CSV Files to Power BI Measures vs Calculated Columns in Power BI Power Query vs DAX: What Goes Where What Is DAX? Beginner Guide for Power BI How CALCULATE Works with Filter Context SUM vs SUMX in Power BI DAX Build Your First Power BI Dashboard How to Use Slicers in Power BI Power BI File Types: PBIX, PBIT and PBIDS Connect SQL Server to Power BI (Import vs DirectQuery) Power BI Import vs DirectQuery vs Dual Power BI Fields, Filters and Visualizations Panes Turn Off Auto Date/Time in Power BI DAX Row Context vs Filter Context DAX Context Transition with CALCULATE Using FILTER Inside CALCULATE in DAX DAX ALL, ALLEXCEPT, ALLSELECTED and REMOVEFILTERS DAX RELATED and RELATEDTABLE DAX KEEPFILTERS with CALCULATE DAX IF and SWITCH Measures DAX DIVIDE for Safe Percentages DAX Year-to-Date TOTALYTD and DATESYTD DAX Month-to-Date and Quarter-to-Date DAX Same Period Last Year and YoY DAX Running Totals DAX RANKX DAX Percentage of Total with ALLSELECTED DAX USERELATIONSHIP for Inactive Relationships DAX VAR and RETURN DAX COUNT, COUNTA, DISTINCTCOUNT and COUNTROWS DAX Rolling 12-Month Average DAX CALCULATETABLE vs FILTER Intermediate DAX Patterns in Power BI How to Choose a Chart in Power BI Power BI Matrix Visual Power BI KPI, Card and Scorecard Power BI Report Page Tooltips Power BI Drill-through Pages Power BI Bookmarks and Buttons Power BI Conditional Formatting Power BI Hierarchy and Drill Down Power BI Field Parameters Power BI Report Layout Design Power Query Applied Steps Power Query Data Types Power Query Duplicate vs Reference Star Schema in Power BI Fact and Dimension Tables in Power BI Power BI Relationships: One to Many Power BI Cardinality and Filter Direction Star vs Snowflake Schema in Power BI Composite Models in Power BI Publish a Power BI Report to the Service Power BI Workspaces and Roles Power BI Apps for Sharing Reports Power BI Dashboard vs Report How to Share a Power BI Report Row-Level Security in Power BI What Is DevOps? Beginner Guide DevOps म्हणजे काय? नवशिक्यांसाठी मार्गदर्शक DevOps क्या है? शुरुआती guide Git Basics for DevOps Beginners DevOps नवशिक्यांसाठी Git Basics DevOps शुरुआती के लिए Git Basics Git Branching and Pull Requests for Beginners नवशिक्यांसाठी Git Branching आणि Pull Requests शुरुआती के लिए Git Branching और Pull Requests Install Docker on EC2 for Beginners नवशिक्यांसाठी EC2 वर Docker Install शुरुआती के लिए EC2 पर Docker Install Your First Dockerfile for Beginners नवशिक्यांसाठी पहिला Dockerfile शुरुआती के लिए पहला Dockerfile Docker Compose for Beginners नवशिक्यांसाठी Docker Compose शुरुआती के लिए Docker Compose Your First GitHub Actions Pipeline तुमची पहिली GitHub Actions Pipeline आपकी पहली GitHub Actions Pipeline Jenkins Pipeline for Beginners नवशिक्यांसाठी Jenkins Pipeline शुरुआती के लिए Jenkins Pipeline Your First Ansible Playbook तुमचा पहिला Ansible Playbook आपका पहला Ansible Playbook Terraform First Apply for Beginners नवशिक्यांसाठी Terraform First Apply शुरुआती के लिए Terraform First Apply DevOps Roadmap 2026: What to Learn in Order DevOps Roadmap 2026: काय शिकावं आणि कोणत्या क्रमाने DevOps Roadmap 2026: क्या सीखें और किस क्रम में DevOps vs SRE vs Platform Engineer: Which Role Fits You? DevOps vs SRE vs Platform Engineer: तुमच्यासाठी कोणती भूमिका? DevOps vs SRE vs Platform Engineer: आपके लिए कौन सी भूमिका? DevOps Engineer Resume Skills Checklist (Fresher and 2+ Years) DevOps Engineer Resume Skills Checklist (Fresher आणि 2+ Years) DevOps Engineer Resume Skills Checklist (Fresher और 2+ Years) How to Prepare for a DevOps Interview in 30 Days DevOps Interview साठी ३० दिवसांत तयारी कशी करायची DevOps Interview की तैयारी 30 दिनों में कैसे करें Linux Commands Every DevOps Engineer Uses Daily दररोज DevOps Engineer वापरतो ती Linux Commands हर दिन DevOps Engineer जो Linux Commands इस्तेमाल करता है Server Health आणि Disk Alerts साठी Bash Script कशी लिहावी Server Health और Disk Alerts के लिए Bash Script कैसे लिखें Cron Jobs Explained: Schedule Backups and Log Cleanup Cron Jobs समजावून: Backups आणि Log Cleanup शेड्यूल करा Cron Jobs समझाया: Backups और Log Cleanup शेड्यूल करें How to Troubleshoot with systemctl and journalctl systemctl आणि journalctl ने Troubleshooting कशी करायची systemctl और journalctl से Troubleshooting कैसे करें Data Science vs Data Analytics vs BI Explained Python for Data Science: Beginner First Steps Install Python 3, venv and Jupyter for Data Science pandas DataFrame for Beginners: Series vs DataFrame pandas read_csv and read_excel for Beginners pandas Filter Rows and Columns (Select, Boolean, Sort) pandas groupby and Aggregation for Beginners Handle Missing Values in pandas (NaN, dropna, fillna) Exploratory Data Analysis (EDA) in Python with pandas matplotlib and seaborn: First Charts for Storytelling Data Science vs Data Analytics vs BI — समजावून सांगितलं Data Science vs Data Analytics vs BI समझाया Data Science साठी Python: नवशिक्यांची पहिली पावलं Data Science के लिए Python: शुरुआती first steps Data Science साठी Python 3, venv आणि Jupyter install Data Science के लिए Python 3, venv और Jupyter install pandas DataFrame नवशिक्यांसाठी: Series vs DataFrame pandas DataFrame शुरुआती: Series vs DataFrame pandas read_csv आणि read_excel नवशिक्यांसाठी pandas read_csv और read_excel शुरुआती pandas मध्ये rows आणि columns filter (select, boolean, sort) pandas में rows और columns filter (select, boolean, sort) pandas groupby आणि aggregation नवशिक्यांसाठी pandas groupby और aggregation शुरुआती pandas मध्ये missing values (NaN, dropna, fillna) pandas में missing values (NaN, dropna, fillna) Python मध्ये EDA (Exploratory Data Analysis) — pandas checklist Python में EDA (Exploratory Data Analysis) — pandas checklist matplotlib आणि seaborn: पहिले charts (storytelling) matplotlib और seaborn: पहले charts (storytelling) Excel VLOOKUP Exact Match (FALSE) for Beginners Excel XLOOKUP Basics for Beginners How to Create a PivotTable in Excel from Scratch Excel IF Function for Decisions (Pass/Fail, High/Low) Excel SUMIF and SUMIFS for Conditional Totals Excel COUNTIF and COUNTIFS Explained Excel INDEX and MATCH Lookup for Beginners How to Remove Duplicates in Excel (Data Tab) Excel CONCAT, TEXTJOIN and & to Join Text Excel FILTER Function (Dynamic Array) for Beginners Excel VLOOKUP Exact Match (FALSE) — मराठी Excel VLOOKUP Exact Match (FALSE) — हिंदी Excel XLOOKUP Basics — मराठी नवशिक्यांसाठी Excel XLOOKUP Basics — हिंदी शुरुआती Excel PivotTable सुरवातीपासून — मराठी Excel PivotTable शुरू से — हिंदी Excel IF Function (High/Low, Pass/Fail) — मराठी Excel IF Function (High/Low, Pass/Fail) — हिंदी Excel SUMIF आणि SUMIFS — मराठी Excel SUMIF और SUMIFS — हिंदी Excel COUNTIF आणि COUNTIFS — मराठी Excel COUNTIF और COUNTIFS — हिंदी Excel INDEX आणि MATCH Lookup — मराठी Excel INDEX और MATCH Lookup — हिंदी Excel Remove Duplicates (Data Tab) — मराठी Excel Remove Duplicates (Data Tab) — हिंदी Excel CONCAT, TEXTJOIN आणि & — मराठी Excel CONCAT, TEXTJOIN और & — हिंदी Excel FILTER Function (Dynamic Array) — मराठी Excel FILTER Function (Dynamic Array) — हिंदी