Shell : Shell script that monitors the disk usage of a specified directory and sends an alert if the disk usage exceeds

Shell Scripting @ Freshers.in

Here we will discuss about a shell script that monitors the disk usage of a specified directory and sends an alert if the disk usage exceeds a certain threshold. This script could be scheduled to run at regular intervals (like every hour) using a tool like cron.

Shell script:

#!/bin/bash

# Check if directory and usage threshold have been provided
if [ $# -ne 2 ]
then
    echo "Usage: $0 <directory> <usage-threshold>"
    exit 1
fi

DIRECTORY="$1"
THRESHOLD="$2"

# Check if the provided directory exists
if [ ! -d "$DIRECTORY" ]
then
    echo "The directory $DIRECTORY does not exist."
    exit 1
fi

# Get the current disk usage
USAGE=$(df "$DIRECTORY" | tail -n 1 | awk '{print $5}' | sed 's/%//')

if [ "$USAGE" -gt "$THRESHOLD" ]
then
    echo "Disk usage of $DIRECTORY is above $THRESHOLD%: ${USAGE}%"
fi

This script accepts two arguments:

  1. The directory that you want to monitor the disk usage of.
  2. The disk usage threshold at which you want to be alerted. This should be a number representing a percentage (like 80 for 80%).

The script first checks if these arguments have been provided and if the directory exists. If these checks pass, the script gets the current disk usage of the directory using the df command. The tail -n 1 part gets the last line of the df output, which is where the disk usage information is. The awk ‘{print $5}’ part gets the fifth field of this line, which is the disk usage as a percentage. The sed ‘s/%//’ part removes the percentage sign.

The script then checks if the current disk usage exceeds the threshold. If it does, it outputs a message to the console. In a real-world use case, you might replace this with code to send an email or trigger some other kind of alert.

This script could be used to keep an eye on disk usage and prevent your disk from filling up without your knowledge. Note that it uses a very simple check and just looks at the disk usage of a single directory. A more sophisticated monitoring solution might take into account other factors and monitor multiple directories or whole disks.

Other urls to refer

Author: user

Leave a Reply