Creating a Linux monitor with Bash

Build a Linux monitoring tool with bash script will track CPU, memory, and disk usage in real time, displaying the usage percentages as they update.
Try the NVMe cloud.

Start your 7-day free trial with no commitment. Explore freely and continue if it’s right for you.

In this project, you’ll develop a linux monitor with bash, using a shell script. The script will track CPU, memory, and disk usage in real time, displaying the usage percentages as they update. Additionally, it will trigger an alert whenever resource usage surpasses predefined thresholds. 

Through this project, you’ll gain essential Linux scripting experience while creating a functional and useful utility.

Tasks

By finishing this project, you will:

  • Gain skills in writing a shell script to monitor system resource usage.
  • Learn to define and implement threshold values for CPU, memory, and disk utilization.
  • Develop a function to trigger alerts when resource usage surpasses the defined limits.

Achievements

Upon completing this project, you will:
  • Have the skills to design and execute a Linux system monitoring tool using a shell script.
  • Gain proficiency in utilizing system resource commands such as top, free, and df.
  • Be prepared to enhance the script with additional features, like email notifications.

Prerequisites

Begin by deploying a cloud instance with an operating system of your choice. For this linux monitoring tool with bash project, you can use the latest Ubuntu version available in our operating systems library, as it offers a suitable environment for coding and testing.

Move into the chosen directory and create a file named system_monitor.sh

				
					cd ~/project
touch system_monitor.sh
				
			

Creating system monitor script

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’s a breakdown of the code’s functionality:

  • #!/bin/bash: This indicates the script is written for the Bash shell.
  • CPU_THRESHOLD=80: This sets the CPU usage alert threshold at 80%, which is adjustable.
  • MEMORY_THRESHOLD=80 and DISK_THRESHOLD=80: These establish the same 80% threshold for memory and disk usage, respectively.

Finally, the instructions are to save the file and make it executable.

				
					chmod +x system_monitor.sh
				
			

Integrating an alert feature

To receive alerts when resource usage is too high, let’s add a new function to system_monitor.sh. Open the file 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)"
}
				
			

This function, send_alert, is designed to send alerts.

It receives two inputs: $1 for the type of resource (like CPU, Memory, or Disk) and $2 for its current usage percentage. To make the alerts stand out, tput setaf 1 changes the text color to red.

After the alert message is displayed, tput sgr0 resets the text formatting back to normal.

It’s recommended to add a test call to verify that the function works correctly. This is an important step for the linux monitor with bash to work correctly.

				
					send_alert "CPU" 85
				
			

Alert function code snippet

Run the script:

				
					./system_monitor.sh
				
			

A red alert message similar to the following should be displayed:

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

Before continuing, delete the test call to send_alert in the script.

Monitoring CPU Usage

To incorporate CPU usage monitoring, the following code should be added to the script.

				
					## Monitoring 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
				
			

This code block performs the following actions:

  • Fetch CPU Stats: Executes the top command in batch mode (-bn1) once to obtain real-time CPU statistics.
  • Isolate CPU Usage: Filters the top command’s output to specifically target the line containing CPU usage information (lines starting with “Cpu(s)”).
  • Calculate Total CPU Usage: Extracts the user and system CPU usage percentages from the filtered output and calculates their sum.
  • Simplify Usage: Removes the decimal portion of the calculated CPU usage for easier comparison with the threshold.
  • Check Threshold: Compares the simplified CPU usage against a predefined CPU_THRESHOLD. If the current usage exceeds the threshold, the send_alert function is called.

Run the script to test CPU monitoring:

				
					./system_monitor.sh
				
			

The displayed CPU usage is constantly monitored. An alert will be generated whenever the usage level surpasses the predetermined threshold.

Monitoring Memory Usage

The next step is to include code that will observe and record memory usage. Insert the following lines of code directly beneath the existing code that monitors CPU activity.

				
					## Monitoring 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
				
			

The functionality of this script can be broken down as follows:

  • The command free is utilized to obtain detailed statistics regarding the system’s memory usage.
  • The awk command is employed to process this information. Specifically, it calculates the percentage of memory currently in use by dividing the amount of used memory (represented by $3) by the total available memory (represented by $2).
  • Finally, the script compares the calculated memory_usage value against a pre-established threshold. If the calculated usage exceeds this threshold, an alert is automatically generated and sent.

Run the script:

				
					./system_monitor.sh
				
			

You will be able to observe the percentage of memory utilization. Alerts will be automatically triggered by the system if the observed memory usage exceeds the established threshold.

Monitoring Disk Usage

The next step is to include code that will observe and record disk usage. Insert the following lines of code directly beneath the existing code that monitors memory activity.

				
					## Monitoring 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
				
			

The functionality of this script can be broken down as follows:

  • The command df -h / is utilized to obtain detailed statistics regarding the disk usage of the root directory.
  • The awk command is employed to process this information and extract the column specifically displaying the disk usage percentage.
  • Subsequently, the script removes the ‘%’ symbol from the extracted usage value to facilitate easier comparison with the established threshold.
  • Finally, the script compares the calculated disk_usage value against a pre-established threshold. If the calculated usage exceeds this threshold, an alert is automatically generated and sent.

Run the script:

				
					./system_monitor.sh
				
			

You will be able to observe detailed statistics pertaining to disk utilization. The system will automatically trigger alerts as required.

Creating a Monitoring Loop

To ensure continuous system monitoring, consolidate the individual checks for CPU utilization, memory usage, and disk space consumption into a single, iterative loop.

Replace the existing code within this section with the following code:

				
					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 operates continuously, monitoring system resource utilization and dynamically updating the displayed information.

At regular intervals, the screen is cleared, and the most recent resource usage statistics are presented.

Run the script to test:

				
					./system_monitor.sh
				
			

Monitoring Tool Summary

Congratulations!

You have successfully developed a fully operational linux monitor with bash scripting language. This valuable tool provides real-time tracking of CPU, memory, and disk usage, and incorporates an alert system to notify you when usage surpasses predefined thresholds. 

We encourage you to further expand the capabilities of this script by integrating features such as email notifications or extending monitoring to encompass additional system resources.

You can also use our platform’s monitoring capabilities for enhanced system visibility.

Thank you for learning with us.

Discover how LifeinCloud can power your projects with our flexible solutions for compute, storage, and networking.

Explore our full range of products

Useful insights?

Help others discover this article by sharing it.