Build a Linux System Monitor Using Bash

LinuxLinuxBeginner
Practice Now

Introduction

In this project, you will learn how to create a Linux system monitor using a shell script. The system monitor will continuously monitor the CPU, memory, and disk usage of your Linux system and display the usage percentages. If any of the thresholds for CPU, memory, or disk usage are exceeded, an alert will be sent. You can customize the threshold values as per your requirements and add your own logic to send alerts.

Linux System Monitor

๐ŸŽฏ Tasks

In this project, you will learn:

  • How to create a shell script to monitor system resources
  • How to set threshold values for CPU, memory, and disk usage
  • How to define a function to send alerts when thresholds are exceeded

๐Ÿ† Achievements

After completing this project, you will be able to:

  • Create a Linux system monitor using a shell script
  • Monitor the CPU, memory, and disk usage of your Linux system
  • Customize the threshold values and add your own logic to send alerts

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL shell(("`Shell`")) -.-> shell/ControlFlowGroup(["`Control Flow`"]) linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/InputandOutputRedirectionGroup(["`Input and Output Redirection`"]) linux(("`Linux`")) -.-> linux/TextProcessingGroup(["`Text Processing`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) linux(("`Linux`")) -.-> linux/SystemInformationandMonitoringGroup(["`System Information and Monitoring`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/VariableHandlingGroup(["`Variable Handling`"]) shell(("`Shell`")) -.-> shell/FunctionsandScopeGroup(["`Functions and Scope`"]) shell(("`Shell`")) -.-> shell/AdvancedScriptingConceptsGroup(["`Advanced Scripting Concepts`"]) shell(("`Shell`")) -.-> shell/SystemInteractionandConfigurationGroup(["`System Interaction and Configuration`"]) shell/ControlFlowGroup -.-> shell/if_else("`If-Else Statements`") linux/BasicSystemCommandsGroup -.-> linux/sleep("`Execution Delaying`") linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/InputandOutputRedirectionGroup -.-> linux/pipeline("`Data Piping`") linux/InputandOutputRedirectionGroup -.-> linux/redirect("`I/O Redirecting`") linux/BasicSystemCommandsGroup -.-> linux/clear("`Screen Clearing`") linux/BasicSystemCommandsGroup -.-> linux/printf("`Text Formatting`") linux/TextProcessingGroup -.-> linux/grep("`Pattern Searching`") linux/TextProcessingGroup -.-> linux/awk("`Text Processing`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/BasicFileOperationsGroup -.-> linux/touch("`File Creating/Updating`") linux/SystemInformationandMonitoringGroup -.-> linux/top("`Task Displaying`") linux/SystemInformationandMonitoringGroup -.-> linux/free("`Memory Reporting`") linux/SystemInformationandMonitoringGroup -.-> linux/df("`Disk Space Reporting`") shell/BasicSyntaxandStructureGroup -.-> shell/shebang("`Shebang`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/BasicSyntaxandStructureGroup -.-> shell/quoting("`Quoting Mechanisms`") shell/VariableHandlingGroup -.-> shell/variables_decl("`Variable Declaration`") shell/VariableHandlingGroup -.-> shell/variables_usage("`Variable Usage`") shell/VariableHandlingGroup -.-> shell/str_manipulation("`String Manipulation`") shell/VariableHandlingGroup -.-> shell/param_expansion("`Parameter Expansion`") shell/ControlFlowGroup -.-> shell/for_loops("`For Loops`") shell/ControlFlowGroup -.-> shell/while_loops("`While Loops`") shell/FunctionsandScopeGroup -.-> shell/func_def("`Function Definition`") shell/AdvancedScriptingConceptsGroup -.-> shell/arith_expansion("`Arithmetic Expansion`") shell/AdvancedScriptingConceptsGroup -.-> shell/cmd_substitution("`Command Substitution`") shell/AdvancedScriptingConceptsGroup -.-> shell/subshells("`Subshells and Command Groups`") shell/AdvancedScriptingConceptsGroup -.-> shell/adv_redirection("`Advanced Redirection`") shell/SystemInteractionandConfigurationGroup -.-> shell/globbing_expansion("`Globbing and Pathname Expansion`") linux/FileandDirectoryManagementGroup -.-> linux/wildcard("`Wildcard Character`") subgraph Lab Skills shell/if_else -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/sleep -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/echo -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/pipeline -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/redirect -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/clear -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/printf -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/grep -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/awk -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/cd -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/touch -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/top -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/free -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/df -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/shebang -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/comments -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/quoting -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/variables_decl -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/variables_usage -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/str_manipulation -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/param_expansion -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/for_loops -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/while_loops -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/func_def -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/arith_expansion -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/cmd_substitution -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/subshells -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/adv_redirection -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} shell/globbing_expansion -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} linux/wildcard -.-> lab-298845{{"`Build a Linux System Monitor Using Bash`"}} end

Create the project files

  1. Open a text editor of your choice.
  2. Create a new file and name it system_monitor.sh.
cd ~/project
touch system_monitor.sh
  1. Copy the following code into the system_monitor.sh file:
#!/bin/bash

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

In this step, we are setting the threshold values for CPU, memory, and disk usage. You can modify these values as per your requirements. The values are set in percentage.

Define the send_alert function

## Function to send an alert
send_alert() {
  echo "$(tput setaf 1)ALERT: $1 exceeded threshold! Current value: $2%$(tput sgr0)"
  ## You can add your own logic here to send an email or notification to the user
}

This function is responsible for sending an alert when any of the threshold values are exceeded. In this code, an alert message is printed to the console using echo. You can customize this function to send alerts via email or notifications to the user.

Define the monitor_system function

## Main function to monitor system resources
monitor_system() {
  while true; do
    ## Get CPU usage percentage
    cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
    cpu_usage=${cpu_usage%.*} ## Convert to integer

    ## Get memory usage percentage
    memory_usage=$(free | awk '/Mem/ {printf("%3.1f", ($3/$2) * 100)}')

    ## Get disk usage percentage of the root directory
    disk_usage=$(df -h / | awk '/\// {print $(NF-1)}')
    disk_usage=${disk_usage%?} ## Remove the % sign

    ## Check if any threshold is exceeded
    if ((cpu_usage >= CPU_THRESHOLD)); then
      send_alert "CPU" "$cpu_usage"
    fi

    if ((memory_usage >= MEMORY_THRESHOLD)); then
      send_alert "Memory" "$memory_usage"
    fi

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

    ## Format and display the output
    clear
    printf "%-15s %s\n" "Resource" "Usage (%)"
    echo "----------------------"
    printf "%-15s %s\n" "CPU Usage" "$cpu_usage"
    printf "%-15s %s\n" "Memory Usage" "$memory_usage"
    printf "%-15s %s\n" "Disk Usage" "$disk_usage"

    sleep 1 ## Adjust the interval as per your preference
  done
}

This function is the main part of the system monitor. It runs an infinite loop to continuously monitor the system resources. Inside the loop, it retrieves the CPU, memory, and disk usage percentages. Then, it checks if any of the thresholds are exceeded and calls the send_alert function if necessary. Finally, it displays the resource usage on the console using printf and echo statements.

Start monitoring the system

## Start monitoring the system
monitor_system

This line of code calls the monitor_system function, which initiates the system monitoring process. Once this line is executed, the system monitor will start running and continuously display the resource usage and check for threshold exceedances.

Save the file

  1. Save the system_monitor.sh file in a location of your choice.
  2. Run the script using the following command:
bash system_monitor.sh
Linux System Monitor

Summary

Congratulations! You have successfully created a Linux system monitor using a bash script. The script monitors the CPU, memory, and disk usage of your Linux system and displays an alert if any resources exceed a set threshold. You can use this script to keep track of resource usage and take necessary actions if required. Remember to adjust the threshold values and the monitoring interval according to your needs.

Other Linux Tutorials you may like