Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Linux Tutorials»Shell Script to Monitor Disk Space and Send Alert

    Shell Script to Monitor Disk Space and Send Alert

    By RahulJanuary 8, 20234 Mins Read

    It is essential to monitor the disk space on a Linux server to ensure enough free space is available for new files and applications. If the disk becomes full, it can cause issues such as system crashes, data loss, and other problems. To prevent these issues, you can use a shell script to monitor the disk space and send an alert when the available space falls below a certain threshold.

    Advertisement

    In this article, we will walk through the process of creating a shell script that monitors the disk space and sends an alert when the available space falls below a certain threshold. We will use the df command to check the available disk space and the mail command to send the alert. The features of this script are:

    • This script can check available free space for multiple disks
    • You can enable to send an email notification
    • You can set the threshold values for Warning and Critical conditions
    • Accept inputs as command line parameters

    Step 1: Shell Script to Check Disk Space

    I have written this shell script that is capable of checking for the available free space on given disks and notifying the admin if the disk space is low. This script required a Bash shell to run. First copy the shell script on your Linux system. In the next steps, I will provide instructions on how to execute it.

    Download this script from GitHub:

  • https://github.com/tecrahul/shell-scripts/blob/master/check-disk-space/check_disk_space.sh
  • Otherwise copy the below shell script and paste it to a file on your server.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    #/usr/bin/env bash
     
    #########################################################################
    #########################################################################
    #
    # This shell script checks for free disk space for defined disks and send
    # email alert based on threshold defined for warning and critical emails
    #
    # Warning and critical thresholds can be passed as command-line parameters
    # The command can be run as:
    #
    # "bash /path/to/script.sh -w 20 -c 10 -d /dev/sda1 -d /"
    #
    # The above script will check free space on /dev/sda1 and disk
    # mounted on the root (/) file system. The script will send a Warning alert
    # if free space is less than 20% of available space and a Critical alert
    # will be sent if free space is less than 10%.
    #
    #   Default warning alert threshold: 20%
    #   Default critical alert threshold: 10%
    #   Default disk to check: /
    #
    #########################################################################
    #########################################################################
     
    ### initializing variables
     
    ## To enable email notification set ENABLE_EMAIL_ALERT to 1
    ENABLE_EMAIL_ALERT=1
    NOTIFICATION_EMAIL="[email protected]"
     
    ## Uncomment and set a custom hostname, default uses the system's hostname
    #HOSTNAME="web-server1"
     
     
    ## Other variables required for the script
     
    THRESHOLD_WARNING=20     #In percent
    THRESHOLD_CRITICAL=10    #In percent
     
    WARNING=0
    CRITICAL=0
     
    WARNING_ALERT=0
    CRITICAL_ALERT=0
     
    ### Create a temporary file to compose an email
    mail_content=`mktemp`
     
     
    ### Read the command line parameters
    while getopts ":w:c:d:" option; do
        case ${option} in
            w)
                THRESHOLD_WARNING=${OPTARG}
                ;;
            c)
                THRESHOLD_CRITICAL=${OPTARG}
                ;;
            d)
                set -f
                disks+=($OPTARG)
                ;;
        esac
    done
     
    send_notification(){
    echo "Sending email notification to ${NOTIFICATION_EMAIL}"
    SUBJECT="${1} ALERT: Host $HOSTNAME Disk Check"
    mail -s ${NOTIFICATION_EMAIL} < ${mail_content}
    }
     
    ### Function to check available space on a given disk
    check_disk_space(){
     
        local total_used_space=`df -h $1 | awk '{print $5}' | tail -1`
        local used_space_percent=`echo ${total_used_space:0:-1}`
        local free_space_percent=$(( 100 - $used_space_percent ))
     
        if (( $free_space_percent <= ${THRESHOLD_CRITICAL} )); then
            CRITICAL=1
            return 2
        elif (( $free_space_percent <= ${THRESHOLD_WARNING} )); then
            WARNING=1
            return 1
        else
            OK=1
            return 0
        fi
    }
     
    ### Check if the disk is passed as command line else select root (/)
    if [ ${#disks[@]} -lt 1 ]; then
            echo "No disk is provided, Selecting root disk as default"
    disks[=]="/"
    fi
     
    ### Create email content
    echo "Attention:
     
    One or more disks are low in space on host \"${HOSTNAME}\".
    " >> ${mail_content}
     
     
    echo ":: CHECK CONDITION"
    echo "-- Warning if free disk is below: ${THRESHOLD_WARNING}%"
    echo "-- Critical if free disk is below: ${THRESHOLD_CRITICAL}%"
     
    echo ":: CHECKING DISKS"
    echo "-- Total disk to check: ${disks[@]}"
     
    ### Calling function check_disk_space for all disk one by one
    for disk in "${disks[@]}"; do
        check_disk_space ${disk}
        if [ ${CRITICAL} -eq 1 ];then
            echo "  => Disk \"${disk}\" is in critical state" | tee -a  ${mail_content}
            CRITICAL_ALERT=1
            CRITICAL=0
        elif [ ${WARNING} -eq 1 ];then
            echo "  => Disk \"${disk}\" is in warning state" | tee -a ${mail_content}
            WARNING_ALERT=1
            WARNING=0
        else
            echo "  => Disk \"${disk}\" is ok"
        fi
    done
     
    ### Finish mail content
     
    echo "
    --
    Thanks
    $HOSTNAME" >>  ${mail_content}
     
    ## Notify if at least one disk is in warning or critical state
    if [ ${CRITICAL_ALERT} -ne 0 ]; then
        [[ $ENABLE_EMAIL_ALERT -eq 1 ]] && send_notification CRITICAL
    elif [ ${WARNING_ALERT} -ne 0 ]; then
        [[ $ENABLE_EMAIL_ALERT -eq 1 ]] && send_notification WARNING
    else
        echo "All disk(s) are okay!"
    fi
     
    #####################      End of Script     ############################

    Step 2: Script Commadn Line Arguments

    You can execute the above script manually or using the system crontab. This script required arguments, that can be passed as command line arguments.

    1. Critical Threshold: Set this parameter to send a critical email alert if the free space (%) is less than this. Use -c command line option to provide custom value. The default value is “10”, if not provided.
    2. Warning Threshold: Set this parameter to send a warning email alert if the free space (%) is less than this but more that the critical value. Use -w command line option to provide custom value. The default value is “20”, if not provided.
    3. Disks to Check: Use -d command line option to provide volume name or mount point to check for free space. You can provide multiple disks by providing them multiple times.

    Step 2: Execute Script Manually

    You can run this script manually or automate it using the system’s crontab. Here are a few examples of how to run this script:

    • Run this script without any arguments.
      bash check_disk_space.sh 
      

      This is similar to:

      bash check_disk_space.sh -c 10 -w 20 -d / 
      
    • Next, you can change the warning and critical alert levels as per your requirements. For example, send a warning notification if the free space is less than 30% and send a critical notification if the free space is less than 15%.
      bash check_disk_space.sh -c 15 -w 30 -d / 
      
    • You can also use the device name instead of the mount point.
      bash check_disk_space.sh -c 15 -w 30 -d /dev/sda1 
      
    • This script also allows the monitoring of multiple disks.
      bash check_disk_space.sh -c 15 -w 30 -d / -d /mnt -d /dev/sda1 
      

    Step 4: Adjust Variables in the Script

    You can adjust a few variables in the script to customize the environment.

    • Set the below option to “1”, to send email notifications.
      ENABLE_EMAIL_ALERT=1
      
    • If the email notification is enabled, Set your email address for sending the notification
      NOTIFICATION_EMAIL="[email protected]"
      
    • Overwrite the default hostname, that will be added in notifications. The default value is the hostname of the system.
      HOSTNAME="web-server1"	
      

    Step 4: Schedule Script with Crontab

    You can also schedule this script using the system’s crontab to automate. Edit the crontab:

    crontab -e 
    

    Add the below crontab entry to run this script hourly.

    1
    2
    ## Monitor disk space
    0   *   *   *   *   bash check_disk_space.sh -w 30 -c 15  -d /

    Save the cron file and close it.

    Conclusion

    In this tutorial, we have provided a bash script that will check for free disk space and send an email notification to the system administrator. This script can monitor multiple disks at a time. Also, you can set custom thresholds for the warning and critical levels.

    disk space monitoring
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    An Introduction to the “./configure” Command: Compiling Source Code in Linux

    Getting Started with Linux Command line: The Beginning

    Backing Up Your Linux System with Rsync: A Step-by-Step Guide

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Test Your Internet Speed from the Linux Terminal
    • 11 Practical Example of cat Command in Linux
    • sleep Command in Linux with Examples
    • 20 Basic Linux Commands for the Beginners (Recommended)
    • tail Command in Linux with Examples
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.