Adding value to global variable in a subshell is not working

爷,独闯天下 提交于 2021-01-29 02:44:05

问题


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:


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



回答2:


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.



来源:https://stackoverflow.com/questions/40801582/adding-value-to-global-variable-in-a-subshell-is-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!