Wednesday, April 9, 2008

UNIX/Linux shell and returning values from functions

Here is an interesting fact.

Let's assume you want to write a function myfun_initialize()

If the function is supposed to initialize some variables then DO NOT RETURN result of this function through the `function caller` (well, I have just made up this name.)

In other words...

right:
myfun_initialize parameters
[ "$var_initialize" = "ok" ] {
echo "Oops!"
return
}

wrong:
[ "`myfun_initialize parameters`" = "ok" ] {
echo "Oops!"
return
}


Why is it wrong? I wish I had a simple explanation, but if the myfun_initialize function initializes some external variables you would like to use later on, then by calling `myfun_initialize` you will initialize temporary variables, and these outside of the call will be unchanged!

Test it yourself:


Here is the text

MYVAR="nothing"

# $1 - value
myfun() {
MYVAR="$1"
}

echo "MYVAR before calling myfun is $MYVAR"
if [ "`myfun something`" = "" ]
then
echo "myfun returned an empty string"
echo "MYVAR after calling \`myfun something \` is $MYVAR"
else
echo "myfun hasn't returned an empty string?!"
echo "MYVAR after calling \`myfun something\` is $MYVAR"
fi

myfun something
echo "MYVAR after calling myfun something is $MYVAR"



So what is the solution?
Use a variable to return the result.
Example:


myfunc() {
....
var_myfunc="ok"
}

myfunc
[ "$myfunc" = "ok" ] && {
...
}

No comments: