Monitoring System Resources with a Shell Script
As a system administrator or a power user, monitoring your system resources is an essential task to ensure optimal performance and avoid unexpected crashes or downtime. While there are many tools available for system monitoring, writing a shell script that provides you with the information you need can be a simple and effective solution.
Here is code :
#!/bin/bash
#author : ajay patel
#date : 19-april-2023
#version :1
while true
do
clear
echo "System Data"
echo "CPU Usage : $(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}' | awk '{printf "%.2f%%\n",$1}')"
echo "memory usage : $(free -m | awk 'NR==2{printf "%.2f%%\n",$3*100/$2 }')"
echo "Disk Usage: $(df -h / | awk 'NR==2{print $5}')"
echo "-----------"
sleep 5
done
Let's go over what this script does:
The script uses an infinite loop to continuously monitor the system resources.
The
clearcommand clears the terminal screen before displaying the latest data.The
topcommand retrieves the CPU usage data and pipes it togrepto find the "Cpu(s)" line. Then,awkextracts the second and fourth columns, adds them together, and formats the result as a percentage.The
freecommand retrieves the memory usage data and pipes it toawkto extract the second line, calculate the percentage of used memory, and format the result as a percentage.The
dfcommand retrieves the disk usage data for the root directory and pipes it toawkto extract the fifth column, which shows the percentage of used disk space.Finally, the script uses the
sleepcommand to pause for 5 seconds before starting the loop again.
In conclusion, writing a Bash script to monitor system resources is an easy and effective way to keep track of your system's performance. With this script, you can quickly identify any issues and take the necessary steps to optimize your system's performance.
Happy coding!



