Thursday, January 20, 2011

bash script to check disk space

Need a script to check whether a certain drive is out of space or hits a certain threshold?

# Extract the disk space percentage capacity -- df dumps things out, sed strips the first line,
# awk grabs the fifth column, and cut removes the trailing percentage.
DISKSPACE=`df -H /dev/sda1 | sed '1d' | awk '{print $5}' | cut -d'%' -f1`

# Disk capacity threshold
ALERT=70
if [ ${DISKSPACE} -ge ${ALERT} ]; then
    echo "Still enough disk space....${DISKSPACE}% capacity."
    exit
fi

5 comments:

  1. here is a more efficient script I wrote.

    #!/bin/bash

    > alert.txt

    HOST=$(hostname)

    THRES=20

    COUNT=1

    df -HP | grep -vE 'Filesystem|tmpfs' | awk '{ print $5 " " $6 }' |
    while read space;

    do

    DISK=$(echo $space | cut -d "%" -f1)
    DRIVENAME=$(echo $space | cut -d " " -f2)

    if [ "$DISK" -ge "$THRES" ]

    then

    echo You have used "$DISK"% on drive "$DRIVENAME" on server "$HOST" >>alert.txt


    fi

    done
    echo alert.txt | mail -s "Disk space Alert on server $HOST" root

    ReplyDelete
  2. Not sure why you consider this approach more efficient. But yes this would probably work too.

    ReplyDelete
  3. Of course the Roger's script is more efficient, clear, legible and a good seed for various tools you need to craft.

    Thanks

    ReplyDelete
  4. I was looking for something more efficient than my solution. But alas. Ok, so here's my $0.02

    In my case, I need to guarantee a certain amount of K are available. The output columns of "df" are not very standardized and in all situations. So be sure to check if yours is the one you want with "df -k | awk '{print $4}' ". The benefits from my approach:
    * 1-liner.
    * Only two process calls (useful in many instances)
    * can be used as part of a shell-boolean expression (ie, if -then construct, boolean shortcut, etc)
    * if mountpoint does not exist, exit code is 1 (false)

    df -k | awk -v mountpt=/WHATEVER -v minreq=MIN-SPACE-IN-KB \
    '$NF == mountpt { found=1; satisfy=($4 >= minreq) ? 1 : 0; } END { exit(!(found && satisfy)); }';

    Here is a more compact, but functionally equivalent version:

    df -k | awk -v t=/WHATEVER -v r=MIN-SPACE-IN-KB \
    '$NF == t { s=($4 >= r) } END { exit(!s); }';

    ReplyDelete