Here's a simple implementation of the send_alert function in a Bash script. This function can send an alert via email or log it to a file. Below are two examples:
Example 1: Send Alert via Email
send_alert() {
local alert_type=$1
local usage=$2
local recipient="your_email@example.com"
echo "Alert: $alert_type usage is at $usage%" | mail -s "$alert_type Alert" "$recipient"
}
Example 2: Log Alert to a File
send_alert() {
local alert_type=$1
local usage=$2
local log_file="/var/log/cpu_alerts.log"
echo "$(date): Alert: $alert_type usage is at $usage%" >> "$log_file"
}
Usage
You can call this function in your script like this:
if ((cpu_usage >= CPU_THRESHOLD)); then
send_alert "CPU" "$cpu_usage"
fi
Notes:
- For the email method, ensure you have a mail transfer agent (like
sendmailorpostfix) configured on your system. - For logging, make sure the script has permission to write to the specified log file.
Feel free to modify the function to suit your alerting needs!
