user2492958
user2492958

Reputation:

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?

Upvotes: 0

Views: 309

Answers (2)

Cyrus
Cyrus

Reputation: 88583

I suggest to insert

shopt -s lastpipe

as new line after

#!/bin/bash

From man bash:

lastpipe: If set, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment.

Upvotes: 1

P.P
P.P

Reputation: 121377

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

Upvotes: 1

Related Questions