从bash中的subshel​​l循环修改全局变量

我的目标是测量当前系统负载的百分比,然后使LED闪烁一秒。为此,我有一个函数“ get_load”,它在while循环中测量一秒钟内的平均负载,并以get_load &之类的子shell运行它。 get_load函数还在每次迭代后定义一个全局LASTLOAD变量。之后,我有一个flip_led函数,它可以打开LED指示灯,休眠1-LASTLOAD秒,将其关闭,然后休眠1-LASTLOAD秒(应合计为一)

问题在于,全局LASTLOAD变量似乎从未更新过,或者至少没有传播到flip_led循环中。

我的问题是如何在子Shell中运行循环,但该子Shell是否会影响初始脚本中的全局变量?

在此脚本本身

readonly LEDTRIGGER="/sys/class/leds/led0/trigger"
readonly LEDBRIGHTnesS="/sys/class/leds/led0/brightness"

LASTLOAD=0
ISRUNNING=1

function get_load() {
    # Define all local variables used in function
    local user1 sys1 idle1 user2 sys2 idle2 u s i load

    while [[ $ISRUNNING -eq 1 ]]; do
        # Get initial usage
        read -r user1 sys1 idle1 \
            <<<"$(grep 'cpu ' /proc/stat | awk '{print $2" "$4" "$5}')"
        sleep 1
        # Get usage after a second has passed
        read -r user2 sys2 idle2 \
            <<<"$(grep 'cpu ' /proc/stat | awk '{print $2" "$4" "$5}')"

        u=$(echo "scale=4;$user2-$user1" | bc)
        s=$(echo "scale=4;$sys2-$sys1" | bc)
        i=$(echo "scale=4;$idle2-$idle1" | bc)

        # Return the average usage over the last second rounded
        load=$(echo "scale=4;($u+$s)*100/($u+$s+$i)" | $BC)
        # loadint=$(echo "($load+0.5)/1" | $BC)
        percent=$(echo "scale=4;$load/100" | $BC)

        # echo "load: $load,loadint: $loadint,percentage: $percent"
        # return "$loadint"
        # echo "$percent"
        LASTLOAD=$percent
        echo "$LASTLOAD"
    done
}

function flip_led() {
    while [[ $ISRUNNING -eq 1 ]]; do
        local remainder
        remainder=$(echo "scale=2;1-$LASTLOAD" | $BC)
        echo 1 | sudo tee $LEDBRIGHTnesS >/dev/null
        echo "led on for $LASTLOAD,off for $remainder"
        $SLEEP "$LASTLOAD"
        echo 0 | sudo tee $LEDBRIGHTnesS >/dev/null
        $SLEEP "$remainder"
    done
}

echo none | sudo tee $LEDTRIGGER >/dev/null
echo 0 | sudo tee $LEDBRIGHTnesS >/dev/null

get_load &
flip_led &

zhufa8888 回答:从bash中的subshel​​l循环修改全局变量

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/1484581.html

大家都在问