2

There is a weird issue where the values of a "Global Variable" is updated in a function but the updated value is lost when i check it in other function. Any help would be appreciated.

#!/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
Amber
  • 1,229
  • 9
  • 29

2 Answers2

1

The while loop executes in a subshell. This is a FAQ; http://mywiki.wooledge.org/BashFAQ/024

tripleee
  • 175,061
  • 34
  • 275
  • 318
0

You are calling your function as:

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

which will execute executeCommand in a sub shell and hence any changes made in any variable will not be available in the parent shell.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • While trimming the script to show just the global variable issue i removed the do and done of while. I apologize. – Amber Jul 22 '14 at 16:34
  • ok I don't get what is `parseResult_$2` doing in your script. Try running your script as `bash -ex ./script.sh` and examine the debug info. – anubhava Jul 22 '14 at 16:36
  • That was a function call but that is tangential to my issue. I have updated that too. – Amber Jul 22 '14 at 16:39
  • ok check updated answer now for the reason of your problem. – anubhava Jul 22 '14 at 16:41
  • Any suggestions on how to get a way around this issue. – Amber Jul 22 '14 at 16:43
  • 1
    Call your function as: `executeCommand "$1"` and instead of `echo "$RESULT"` use another global variable to hold `$RESULT` variable. – anubhava Jul 22 '14 at 16:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/57777/discussion-between-amber-and-anubhava). – Amber Jul 22 '14 at 17:10