0

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?

1
  • 2
    You are running a sub-shell, variables tend to get lost during post its exit Commented Nov 25, 2016 at 9:32

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.