Build a Linux System Monitor Using Bash

LinuxLinuxBeginner
Practice Now

Introduction

In this project, you will create a Linux system monitor using a shell script. This script will continuously track the CPU, memory, and disk usage of your system, displaying the usage percentages in real time. If the usage of any resource exceeds a preset threshold, an alert will be displayed. By completing this project, you will learn foundational Linux scripting skills while building a practical tool.

Linux System Monitor

๐ŸŽฏ Tasks

By completing this project, you will:

  • Learn how to create a shell script to monitor system resources.
  • Understand how to set and use threshold values for CPU, memory, and disk usage.
  • Create a function to send alerts when thresholds are exceeded.

๐Ÿ† Achievements

After completing this project, you will:

  • Be able to create and run a Linux system monitor using a shell script.
  • Understand how to work with system resource commands like top, free, and df.
  • Be equipped to extend the script by adding new features, such as email notifications.

Setting Up the Project

Start by preparing a clean workspace for your script. We recommend using WebIDE for this project, as it suits coding and testing scripts.

Navigate into this directory and create a file named system_monitor.sh:

cd ~/project
touch system_monitor.sh
alt text

Open the file in your favorite text editor and add the following lines:

#!/bin/bash

## Define the threshold values for CPU, memory, and disk usage (in percentage)
CPU_THRESHOLD=80
MEMORY_THRESHOLD=80
DISK_THRESHOLD=80

Here is what each part of the code does:

  • #!/bin/bash: This line specifies that the script will be interpreted using the Bash shell.
  • CPU_THRESHOLD=80: Sets the CPU usage threshold to 80%. You can adjust this value later.
  • MEMORY_THRESHOLD=80 and DISK_THRESHOLD=80: Similarly, these define thresholds for memory and disk usage.

Save the file and make it executable:

chmod +x system_monitor.sh

Adding an Alert Function

Now, letโ€™s add a function to send alerts when resource usage exceeds the thresholds. Open system_monitor.sh and add the following code:

## Function to send an alert
send_alert() {
  echo "$(tput setaf 1)ALERT: $1 usage exceeded threshold! Current value: $2%$(tput sgr0)"
}

Here is a breakdown of this function:

  • send_alert: The function takes two arguments:
    • $1 represents the resource type (e.g., CPU, Memory, Disk).
    • $2 represents the current usage percentage.
  • tput setaf 1: Changes the text color to red to make alerts visually distinct.
  • tput sgr0: Resets the text formatting to normal after the alert message.

Add a test call to the function to verify it works:

send_alert "CPU" 85
alt text

Run the script:

./system_monitor.sh

You should see a red alert message similar to:

ALERT: CPU usage exceeded threshold! Current value: 85%

Before moving on, delete the test call to send_alert from the script.

Monitoring CPU Usage

Letโ€™s add logic to monitor CPU usage. Open the script and add the following code:

## Monitor CPU usage
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
cpu_usage=${cpu_usage%.*} ## Convert to integer
echo "Current CPU usage: $cpu_usage%"

if ((cpu_usage >= CPU_THRESHOLD)); then
  send_alert "CPU" "$cpu_usage"
fi

Hereโ€™s what happens in this code:

  1. top -bn1: Runs the top command in batch mode for one iteration to fetch real-time CPU stats.
  2. grep "Cpu(s)": Filters the output to focus on the CPU usage line.
  3. awk '{print $2 + $4}': Extracts and sums the percentages of user and system CPU usage.
  4. cpu_usage=${cpu_usage%.*}: Strips the decimal part to simplify threshold comparisons.
  5. if ((cpu_usage >= CPU_THRESHOLD)): Compares the CPU usage with the threshold and calls send_alert if itโ€™s exceeded.

Run the script to test CPU monitoring:

./system_monitor.sh

You should see the CPU usage displayed. If itโ€™s above the threshold, youโ€™ll see an alert.

Monitoring Memory Usage

Next, add code to monitor memory usage. Insert the following lines below the CPU monitoring logic:

## Monitor memory usage
memory_usage=$(free | awk '/Mem/ {printf("%3.1f", ($3/$2) * 100)}')
echo "Current memory usage: $memory_usage%"
memory_usage=${memory_usage%.*}
if ((memory_usage >= MEMORY_THRESHOLD)); then
  send_alert "Memory" "$memory_usage"
fi

Hereโ€™s how it works:

  1. free: Provides memory usage stats.
  2. awk '/Mem/ {printf("%3.1f", ($3/$2) * 100)}': Calculates the percentage of memory in use by dividing used memory ($3) by total memory ($2).
  3. The script compares memory_usage with the threshold and sends an alert if necessary.

Run the script:

./system_monitor.sh

You should see the memory usage percentage, and alerts will trigger if the usage exceeds the threshold.

Monitoring Disk Usage

Now, letโ€™s monitor disk usage. Add the following code below the memory monitoring logic:

## Monitor disk usage
disk_usage=$(df -h / | awk '/\// {print $(NF-1)}')
disk_usage=${disk_usage%?} ## Remove the % sign
echo "Current disk usage: $disk_usage%"

if ((disk_usage >= DISK_THRESHOLD)); then
  send_alert "Disk" "$disk_usage"
fi

Explanation:

  1. df -h /: Fetches disk usage stats for the root directory.
  2. awk '/\// {print $(NF-1)}': Extracts the usage percentage column.
  3. disk_usage=${disk_usage%?}: Removes the % symbol for easier comparisons.
  4. Alerts are triggered if the disk usage exceeds the threshold.

Run the script:

./system_monitor.sh

You should see disk usage statistics, and alerts will trigger if necessary.

Combining Everything into a Loop

Finally, combine the CPU, memory, and disk monitoring into a loop for continuous monitoring. Replace the existing content with this:

while true; do
  ## Monitor CPU
  cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
  cpu_usage=${cpu_usage%.*}
  if ((cpu_usage >= CPU_THRESHOLD)); then
    send_alert "CPU" "$cpu_usage"
  fi

  ## Monitor memory
  memory_usage=$(free | awk '/Mem/ {printf("%3.1f", ($3/$2) * 100)}')
  memory_usage=${memory_usage%.*}
  if ((memory_usage >= MEMORY_THRESHOLD)); then
    send_alert "Memory" "$memory_usage"
  fi

  ## Monitor disk
  disk_usage=$(df -h / | awk '/\// {print $(NF-1)}')
  disk_usage=${disk_usage%?}
  if ((disk_usage >= DISK_THRESHOLD)); then
    send_alert "Disk" "$disk_usage"
  fi

  ## Display current stats
  clear
  echo "Resource Usage:"
  echo "CPU: $cpu_usage%"
  echo "Memory: $memory_usage%"
  echo "Disk: $disk_usage%"
  sleep 2
done

This loop continuously monitors and updates resource usage, clearing the screen and displaying current stats at regular intervals.

Run the script to test:

./system_monitor.sh

Summary

Congratulations! Youโ€™ve built a fully functional Linux system monitor using Bash. This tool tracks CPU, memory, and disk usage in real time, alerting you if usage exceeds predefined thresholds. Feel free to extend the script by adding features like email notifications or monitoring additional resources.

Linux System Monitor

Other Linux Tutorials you may like