Skip to main content

Command Palette

Search for a command to run...

Monitoring System Resources with a Shell Script

Updated
2 min read

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 clear command clears the terminal screen before displaying the latest data.

  • The top command retrieves the CPU usage data and pipes it to grep to find the "Cpu(s)" line. Then, awk extracts the second and fourth columns, adds them together, and formats the result as a percentage.

  • The free command retrieves the memory usage data and pipes it to awk to extract the second line, calculate the percentage of used memory, and format the result as a percentage.

  • The df command retrieves the disk usage data for the root directory and pipes it to awk to extract the fifth column, which shows the percentage of used disk space.

  • Finally, the script uses the sleep command 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!

More from this blog

Ajay Patel

116 posts