Search code examples
bashshelldisk

Error on a disk space usage script


I tried to modify a little script of checking disk space usage, and I faced the below error:

disk_space.sh: line 32: [: Use: integer expression expected

# Set alert limit, 90% we remove % for comparison
alert=90

# $1 is the partition name
# $5 is the used percentage
# Print the df -h, then loop and read the result 
df -h | awk '{ print $1 " " $5 }' | while read output;
do

#echo $output

# Get partition name
partition=$(echo $output | awk '{ print $1 }')
#echo 'Partition: ' $partition

# Used space with percentage
useSpPer=$(echo $output | awk '{ print $2}')
#echo 'Used space %: ' $useSpPer

#used space (remove percentage)
useSp=$(echo -n $useSpPer | head -c -1)
#echo 'Used space digit: ' $useSp

# Recap
#echo $useSp ' has ' $partition

# -ge is greatter than or equal
if [ $useSp -ge $alert ]; then # THIS LINE 32
echo $partition 'is running out of space with '$useSpPer

#else 
#echo 'Down'

fi
done

If anyone has an idea, appreciated it and thanks in advance


Solution

  • Putting set -x at the top of your script so that it echoes each line before execution is a great way to debug shell scripts - you'll almost certainly find that one of those variables (used in the [ command) isn't being set as you expected.

    That's good general advice but, for this problem where you've localised the problem, it's probably good enough (and certainly less verbose) to place this line before the line generating the problem:

    echo "DEBUG [$useSp]"
    

    If you do that, you'll find that the value you're checking is not a numeric value at all. That's because the output of df -h looks something like this:

    Filesystem  Size  Used  Avail  Use%  Mounted on
    /dev/sda1    48G  4.9G    40G   11%  /
    /dev/sr0     71m   71M      0  100%  /media/cdrom0
    

    That means that, for the first line, you'll be comparing the word Use against your limit and [ will not handle that well:

    pax> if [ 20 -gt 10 ]; then echo yes; fi
    yes
    pax> if [ Use -gt 10 ]; then echo yes; fi
    bash: [: Use: integer expression expected
    

    The fix is fairly simple. Since you don't want to do anything with the first line, you can just use your existing awk to filter it out:

    df -h | awk 'NR>1{print $1" "$5}' | while read output;
    do
        ...
    

    The NR>1 only processes record numbers two and so on, skipping the first one.