Automation Lab 2 - Bash System Health Check

This lab shows a Bash script that checks core Linux health metrics, compares results against thresholds, and outputs a timestamped status summary for review or logging.

Overview

Reliable operations depend on quick visibility into host performance and service status. This script combines CPU, memory, disk, and service checks into one repeatable command line workflow.

Real-world relevance: Early detection of resource pressure and service failures supports faster response and helps prevent preventable outages.

Objective

Script Walkthrough

  1. Set threshold variables for CPU, memory, and disk usage for quick adjustment.
  2. Used top and awk to calculate current CPU utilization.
  3. Parsed free output to compute memory usage percentage.
  4. Used df to capture root partition disk usage percentage.
  5. Checked each critical service with systemctl is-active and recorded status.
  6. Printed a formatted summary and appended output to a log file for historical review.

Script Preview

#!/bin/bash
# Automation Lab 2 - Bash System Health Check
# Checks CPU, memory, disk, and service status with threshold alerting

TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
LOG_FILE="/var/log/system_health.log"

CPU_THRESHOLD=80
MEM_THRESHOLD=85
DISK_THRESHOLD=90

SERVICES=("ssh" "cron")

GREEN='\033[0;32m'
RED='\033[0;31m'
RESET='\033[0m'

echo "====================================="
echo " System Health Check - $TIMESTAMP"
echo "====================================="

# CPU Usage
CPU_IDLE=$(top -bn1 | grep "Cpu(s)" | awk '{print $8}' | tr -d '%')
CPU_USED=$(echo "100 - $CPU_IDLE" | bc)
if (( $(echo "$CPU_USED > $CPU_THRESHOLD" | bc -l) )); then
    echo -e "CPU Usage:    ${RED}${CPU_USED}% - ALERT${RESET}"
else
    echo -e "CPU Usage:    ${GREEN}${CPU_USED}% - OK${RESET}"
fi

# Memory Usage
MEM_TOTAL=$(free | awk '/Mem:/ {print $2}')
MEM_USED=$(free  | awk '/Mem:/ {print $3}')
MEM_PCT=$(echo "scale=1; $MEM_USED / $MEM_TOTAL * 100" | bc)
if (( $(echo "$MEM_PCT > $MEM_THRESHOLD" | bc -l) )); then
    echo -e "Memory Usage: ${RED}${MEM_PCT}% - ALERT${RESET}"
else
    echo -e "Memory Usage: ${GREEN}${MEM_PCT}% - OK${RESET}"
fi

# Disk Usage
DISK_USED=$(df / | awk 'NR==2 {print $5}' | tr -d '%')
if [ "$DISK_USED" -gt "$DISK_THRESHOLD" ]; then
    echo -e "Disk Usage:   ${RED}${DISK_USED}% - ALERT${RESET}"
else
    echo -e "Disk Usage:   ${GREEN}${DISK_USED}% - OK${RESET}"
fi

# Service Checks
echo ""
echo "Service Status:"
for SERVICE in "${SERVICES[@]}"; do
    STATUS=$(systemctl is-active "$SERVICE" 2>/dev/null)
    if [ "$STATUS" = "active" ]; then
        echo -e "  $SERVICE: ${GREEN}Running${RESET}"
    else
        echo -e "  $SERVICE: ${RED}NOT Running - ALERT${RESET}"
    fi
done

echo "=====================================" | tee -a "$LOG_FILE"
echo "Check complete. See $LOG_FILE for history."

Key Skills Demonstrated

Tools & Technologies

Results & Outcomes

← Back to Automation Scripts
↑ Top