Shell脚本中丢失了全局变量中的更新值

时间:2014-07-22 16:28:14

标签: linux bash shell

有一个奇怪的问题,“全局变量”的值在函数中更新,但当我在其他函数中检查时,更新的值会丢失。任何帮助将不胜感激。

#!/bin/bash

FINAL_RESULT="";
COMMAND_RESULT="";

function init() {
    USERNAME="root";
    DF_THRESHOLD="20";
    DF_COMMAND="df -Pkh";
}

function executeCommand() {
    local RESULT;
    SERVER=$(hostname);
    RESULT=$($1);
    FINAL_RESULT="$FINAL_RESULT -------------------------- Executing command : \"$1\" on \"$SERVER\" --------------------------"
    echo "Updating FINAL_RESULT to $FINAL_RESULT"   # Updated value is present
    echo "$RESULT"
    COMMAND_RESULT="$RESULT"
}

function getCommandResult() {
executeCommand "$1";
echo "$COMMAND_RESULT" | while read eachLine
    do  
    if [ "$eachLine" != "" ]; then
        echo "----------- eachLine ----------- $eachLine"
    fi
    done
    echo "Found FINAL_RESULT as $FINAL_RESULT"   # Updated values is lost
}

function main() {
    init
    getCommandResult "$MMGETSTATE_COMMAND" "MMGETSTATE";
}

main
echo "*** $FINAL_RESULT"   # Even now the updated values are not found

2 个答案:

答案 0 :(得分:1)

while循环在子shell中执行。这是一个FAQ; http://mywiki.wooledge.org/BashFAQ/024

答案 1 :(得分:0)

您正在将您的职能称为:

local DF_Result="$( executeCommand "$1" )"

将在子shell中执行executeCommand,因此在任何变量中所做的任何更改都不会在父shell中可用。