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.
Prerequisites
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:
- 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. - Variable Declaration: Here we declare variables that will be used in the script.
- Usage Function: This function provides information on how to use the script.
- Error Handling: This section checks for any potential errors that may occur during script execution.
- 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:
#!/bin/bash
# Variable Declaration
INTERVAL=5 # Default monitoring interval in seconds
# Usage Function
usage() {
echo "Usage: $0 [-i interval]"
echo
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
i)
INTERVAL=$OPTARG
;;
?)
usage
;;
esac
done
# Error Checking
if [[ -z "$INTERVAL" ]]; then
echo "ERROR: Interval is mandatory."
usage
fi
if ! [[ "$INTERVAL" =~ ^[0-9]+$ ]]; then
echo "ERROR: Interval must be a positive integer."
exit 1
fi
# 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 --"
uptime
sleep $INTERVAL
done
Using the Script
To use this script, follow these steps:
- Save the script in a file, such as
monitor_resources.sh
. - Make the script executable by running
chmod +x monitor_resources.sh
. - 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.