【问题标题】:Adding value to global variable in a subshell is not working在子shell中向全局变量添加值不起作用
【发布时间】:2016-11-25 09:29:38
【问题描述】:

我正在尝试获取我的机器的总磁盘使用量。下面是脚本代码:

#!/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 相加:

totalUsage=$((totalUsage+diskUsage))

dodone 之间的 totalUsage 回显显示正确的值, 但是当我在调用diskUse 后尝试回显它时,它仍然会打印0

你能帮帮我吗,这里出了什么问题?

【问题讨论】:

  • 你正在运行一个子shell,变量在退出后往往会丢失

标签: bash shell


【解决方案1】:

子 shell 中的变量 totalUsage 不会改变父 shell 中的值。 由于您标记了 bash,您可以使用 here string 来修改您的循环:

#!/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】:

我建议插入

shopt -s lastpipe

之后换行

#!/bin/bash

来自man bash

lastpipe:如果设置,并且作业控制未激活,shell 将运行当前 shell 环境中未在后台执行的管道的最后一个命令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-13
    • 2017-05-20
    • 2013-09-21
    • 1970-01-01
    • 2021-03-06
    • 2016-12-30
    • 1970-01-01
    相关资源
    最近更新 更多