Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scope of variable in pipe

Tags:

shell

pipe

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
like image 759
shantanuo Avatar asked Feb 28 '23 00:02

shantanuo


1 Answers

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
like image 157
glenn jackman Avatar answered Mar 02 '23 14:03

glenn jackman