Introduction
Monitoring free RAM is crucial for maintaining system performance, especially in production environments where resource constraints can impact applications. In this blog, we'll create a simple Bash script to monitor available RAM and send alerts if it falls below a specified threshold.
Prerequisites
- Before proceeding, ensure you have:
- A Linux-based system (Ubuntu, CentOS, etc.)
- Basic knowledge of Bash scripting
- Access to free, awk, and mail commands
Understanding Free RAM Command
To check available RAM on a Linux system, we use the free command:
If we want a total column of memory and swap then we can use "free -mt"
But this is not human readable format . To make it human readable we can use " -h " command.
Now we can take out only the total row also using "grep" ( global regular expression print)
Here after grep we used expression "Total" means it will all rows which will have "Total" string in it.
We can also use awk after grep to take out fixed column also like, if i want to takeout only "free" column then i can use "awk '{print $4}' as free column number is 4.
We will focus on the free column to determine how much memory is completely unused by the system.
Writing the Bash Script
Let's create a Bash script that:
- Retrieves free RAM.
- Compares it with a threshold value.
- Sends an alert if RAM is below the threshold.
Step 1: Create the script file
touch monitor_free_ram.sh
chmod +x monitor_free_ram.sh
vi monitor_free_ram.sh
Step 2: Add the script content
#!/bin/bash
# Define RAM threshold (in MB)
THRESHOLD=500 # Adjust as needed
# Get free RAM
FREE_RAM=$(free -mt | grep "Total" | awk '{print $4}')
# Log current status
echo "Free RAM: $FREE_RAM MB"
# Check if free RAM is below threshold
if [[ "$FREE_RAM" -lt "$THRESHOLD" ]]; then
MESSAGE="Warning: Low Free RAM! Only $FREE_RAM MB free."
echo "$MESSAGE"
# Send email alert (Requires configured mail service)
echo "$MESSAGE" | mail -s "Low Free RAM Alert"
souravbit3366@gmail.com
fi
How the Script Works
- We set a threshold value (e.g., 500MB).
- The script extracts the free RAM using free -m and awk.
- If the free RAM falls below the threshold, a warning message is printed and emailed.
Automating the Script with Cron Job
To run this script automatically, schedule a cron job:
crontab -e
Add this line to check every 5 minutes:
*/5 * * * * /path/to/monitor_free_ram.sh >> /var/log/ram_monitor.log 2>&1
Conclusion
This simple script helps monitor system memory and prevent performance issues. We can extend it by logging alerts, integrating it with monitoring tools like Prometheus, or sending notifications via Slack or Telegram.
Top comments (1)
How to configure mail service?