/ Bash Scripts

Monitor system resources

This guide provides instructions on how to create a Bash script to monitor system resources. The script will monitor CPU usage, memory usage, disk space, and system load. Custom settings and options can be provided by the user.


This guide assumes you have the following:

  • A Linux operating system with a Bash shell environment.
  • Basic knowledge of Bash scripting, such as creating, editing, and executing scripts.
  • Basic knowledge of system monitoring commands such as top, free, df, uptime.

Script Structure

Let’s break down the script into various sections:

  1. Shebang: The shebang #!/bin/bash at the beginning of the script informs the system that the script is to be executed by the Bash shell.
  2. Variable Declaration: Here we declare variables that will be used in the script.
  3. Usage Function: This function provides information on how to use the script.
  4. Error Handling: This section checks for any potential errors that may occur during script execution.
  5. Main Logic: The main logic of the script where the monitoring of system resources happens.

Creating the Bash Script

Below is the entire bash script with comments explaining each section:


# Variable Declaration
INTERVAL=5  # Default monitoring interval in seconds

# Usage Function
usage() {
  echo "Usage: $0 [-i interval]"
  echo "Options:"
  echo "  -i interval : Monitoring interval in seconds (default is 5 seconds)"
  exit 1

# Parse Command Line Arguments
while getopts "i:" OPTION; do
  case $OPTION in

# Error Checking
if [[ -z "$INTERVAL" ]]; then
  echo "ERROR: Interval is mandatory."

if ! [[ "$INTERVAL" =~ ^[0-9]+$ ]]; then
  echo "ERROR: Interval must be a positive integer."
  exit 1

# Main Logic
while true; do
  echo "-------- System Resource Monitor ---------"
  echo "---- $(date) ----"

  echo "-- CPU Usage --"
  top -b -n1 | grep "Cpu(s)" 

  echo "-- Memory Usage --"
  free -h

  echo "-- Disk Space Usage --"
  df -h

  echo "-- System Load --"

  sleep $INTERVAL

Using the Script

To use this script, follow these steps:

  1. Save the script in a file, such as monitor_resources.sh.
  2. Make the script executable by running chmod +x monitor_resources.sh.
  3. Run the script with your desired options. For example, to monitor system resources every 10 seconds, run:
./monitor_resources.sh -i 10

Without the -i option, the script will use the default interval of 5 seconds.

This script is flexible and customizable, allowing you to monitor system resources based on your specific needs. Refer back to this documentation whenever necessary to understand the functionality and usage of the script.

Was this helpful?

Thanks for your feedback!