ADPK ADPK - 10 days ago 6
Bash Question

Adding value to global variable in a subshell is not working

I am trying to get the total disk usage of my machine. Below is the script code:

#!/bin/sh
totalUsage=0
diskUse(){
df -H | grep -vE '^Filesystem|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
diskUsage=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
totalUsage=$((totalUsage+diskUsage))
done
}
diskUse
echo $totalUsage


While
totalUsage
is a global variable, I have tried to sum the individual disk usage to
totalUsage
in the line:

totalUsage=$((totalUsage+diskUsage))


An echo of
totalUsage
between
do
and
done
shows the correct value,
but when I try to echo it after my call
diskUse
, it stills prints a
0


Can you please help me, what is wrong here?

Answer

The variable totalUsage in a sub-shell doesn't change the value in the parent shell. Since you tagged bash, you can use here string to modify your loop:

#!/bin/bash
totalUsage=0
diskUse(){
    while read output;
    do
       diskUsage=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
       totalUsage=$((totalUsage+diskUsage))
    done <<<"$(df -H | grep -vE '^Filesystem|cdrom' | awk '{ print $5 " " $1 }')"
}
diskUse
echo $totalUsage
Comments