The following shell scrip will check the disk space and change the variable diskfull
to 1
if the usage is more than 10%
The last echo always shows 0
I tried the global diskfull=1
in the if clause but it did not work.
How do I change the variable to 1
if the disk consumed is more than 10%?
#!/bin/sh
diskfull=0
ALERT=10
df -HP | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
#echo $output
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge $ALERT ]; then
diskfull=1
exit
fi
done
echo $diskfull
@OP, use an outer brace or ()
This is a side-effect of using
while
in a pipeline. There are two workarounds:1) put the
while
loop and all the variables it uses in a separate scope as demonstrated by levislevis862) if your shell allows it, use process substitution and you can redirect the output of your pipeline to the input of the while loop
In this line:
it's not necessary to use
cut
. You can do this:you can do it this way with gawk(no need to use grep). for alerts you can send email to root.
or check whether there is "msg" or not first
I think you must not be getting to the
diskfull=1
line, because if you were, you would get no output at all-- the followingexit
line would exit the script.I don't know why this isn't working, but note that awk can handle the rest of the work:
This way you don't need the while loop.
When using pipes the shell seams to use sub-shells to do the work. As
$diskfull
is not known to these sub-shells the value is never changed.See: http://www.nucleardonkey.net/blog/2007/08/variable_scope_in_bash.html
I modified your script as follows. It works for me and should work on your system too.