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
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 levislevis86
some | complicated | pipeline | {
while read line; do
foo=$( some calculation )
done
do_something_with $foo
}
# $foo not available here
2) if your shell allows it, use process substitution and you can redirect the output of your pipeline to the input of the while loop
while read line; do
foo=$( some calculation )}
done < <(some | complicated | pipeline)
do_something_with $foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With