在子shell中向全局变量添加值不起作用 [英] 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
虽然 totalUsage
是全局变量,但我尝试将以下行中的单个磁盘使用量汇总为 totalUsage
:
While totalUsage
is a global variable, I have tried to sum the individual disk usage to totalUsage
in the line:
totalUsage = $(((totalUsage + diskUsage))
在 do
和 done
之间的 totalUsage
回显显示正确的值,但是当我在调用 diskUse
后尝试回显它时,它仍然会打印 0
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?
推荐答案
子外壳中的变量 totalUsage
不会更改父外壳中的值.由于标记了bash,因此可以使用此处字符串修改循环:
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
这篇关于在子shell中向全局变量添加值不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!