Sign up to get Free Ebooks...

I hope you enjoy reading this article. If you are looking for such article ,Click here


Script for monitoring disk space in Linux for Centos and Ubuntu operating system

  • Home
  • /
  • Blog
  • /
  • Script for monitoring disk space in Linux for Centos and Ubuntu operating system
#!/bin/bash
# Set the threshold value for disk usage in percentage
THRESHOLD=80
# Get the disk usage for each partition and check if it is above the threshold
if [ -f /etc/redhat-release ]; then
# CentOS
for partition in $(df -h | awk '{print $6}' | grep -v "Mounted"); do
USAGE=$(df -h | grep "$partition" | awk '{print $5}' | sed 's/%//')
if [ $USAGE -gt $THRESHOLD ]; then
echo "Warning: Disk usage for $partition is above threshold of $THRESHOLD%"
fi
done
elif [ -f /etc/lsb-release ]; then
# Ubuntu
for partition in $(df -h | awk '{print $6}' | grep -v "Mounted"); do
USAGE=$(df -h | grep "$partition" | awk '{print $5}' | sed 's/%//')
if [ $USAGE -gt $THRESHOLD ]; then
echo "Warning: Disk usage for $partition is above threshold of $THRESHOLD%"
fi
done
else
echo "Unsupported operating system"
exit 1
fi

In this script, the THRESHOLD variable is set to 80, which represents the percentage of disk usage that should trigger an alert. The script first checks if the operating system is CentOS or Ubuntu by checking the existence of the /etc/redhat-release or /etc/lsb-release file.

The script then uses the df command to get the disk usage for each partition. For both CentOS and Ubuntu, the awk command is used to extract the partition names from the sixth column of the df output, and the grep -v "Mounted" command is used to exclude the header row.

The script then uses the grep and awk commands to extract the usage percentage from the fifth column of the df output and removes the percentage symbol using the sed command. The script then checks if the usage percentage is above the threshold and prints a warning message to the console if it is.

This script can be run as a cron job at regular intervals to continuously monitor the disk usage of your CentOS or Ubuntu system and alert you if it exceeds the specified threshold.



November 11, 2024

November 11, 2024

November 11, 2024

June 19, 2023

May 31, 2023

May 9, 2023

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>