1

I have the following simple script. In this script, I am assigning a value to a global variable inside a function. I can clearly see that the value is being assigned to the variable via a debug statement. However, when I echo the variable at the end, it's always empty.

function getValue()
{
local key=$1
local configFile=$2
keyValuePair="$(egrep "$key" "$configFile")" 

if [ ! "$?" -eq 0 ]
then
    echo "Cannot find the value for the specifed key"
    return 1;   
fi

value="$(cut -d"=" -f"2" <<< "$keyValuePair")"
echo "$value"
return 0;
}
function configuer()
{
if [ ! -f "$RMCFGFILE" ]
then
    echo "Cannot file RMGCFG file."
    return 1;
fi

#Recyclebin configuration
value=$(getValue "recyclebin" $RMCFGFILE)
if [ ! "$?" -eq 0 ]
then
    echo "$value"
    return 1;
fi

RECYCLEBIN="$value" **#### I am assigning here**
return 0;
 }
RECYCLEBIN=
RMCFGFILE="/home/sas/.rm.cfg"
LOCALEFILE=""
CONFIG_RESULT=$(configuer)

if [ ! "$?" -eq 0 ]
then
echo "$CONFIG_RESULT"
exit 1;
fi

echo "Configuration success"
eval echo "Recyclebin: ${RECYCLEBIN}" **##No value**

Does anyone see what's going wrong here??

  • 1
    Which of the multiple functions and variables are you talking about? What debug statement are you refering to? – Gilles Jun 13 '14 at 0:33
  • 1
    What are you expecting value=$(getValue "recyclebin" $RMCFGFILE) to do? – steeldriver Jun 13 '14 at 0:50
  • I think RECYCLEBIN= ; ... ; echo "$RECYCLEBIN" is the problem - You assign it the '' null string. You could try echo "${RECYCLEBIN+set but empty}" to find out. But get rid of eval. – mikeserv Jun 13 '14 at 1:04
2

You're expecting:

CONFIG_RESULT=$(configuer)

To assign a value to $RECYCLEBIN because you...

RECYCLEBIN="$value"

... in the configuer() function. It's true that the function does assign a value to $RECYCLEBIN but that value only persists for the duration of the $(subshell) in which you set it. It will not apply any changes to its parent shell's environment - which is where you call it. When you:

eval echo "Recyclebin: ${RECYCLEBIN}"

eval parses all of its arguments out into a space separated string and attempts to run the results as a shell command. So "${RECYCLEBIN}" disappears because - in the current shell environment - it was last set to the '' null string like:

RECYCLEBIN=

So on its execution of the statement all it does is:

echo Recyclebin:

Which is functionally no different than...

echo "Recyclebin: ${RECYCLEBIN}"

...anyway because $RECYCLEBIN is empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.