Wednesday, October 2, 2013

Query in Function Call in Shell Script

www.unixbabuforum.inSee this bash script and tell that does the bash allows access of a local variable of one function in another function ? 



echo "inside f1" 
local X=2 
echo "Return code: $F2" 
echo "value of F3: $F3" # In C, you cann't access value of another functn 
# just by calling it. 

echo "outside functns: $X" 


echo "value of X: $X" # In C, you cann't access value of another functn 
# just by calling it. 
echo "inside f2" 
if [ 1 ];then 
echo "true" 
echo "false" 
return 5 



www.unixbabuforum.inf1 () contains the definition: local X=2 

f2 () contains the definition F3=6 

Now, just what exactly would you expect the "local" keyword to mean in a function? 

This is not mixing C and shell, it is only the comments that mention C to highlight the differences. 

In C, automatic stack variables are available only in that function. You can extern them to use a global variable of that name. 

In shells, variables are by default global. The keywords local (bash) and typeset (ksh and bash) make those variable names private to a function. 

The hard thing to get is that the scope of shell variables is largely determined by process protection rules, NOT syntactic rules. 

Your use of if [ 1 ] is also not doing what you think. Sure, it is true. But then if [ 0 ] is true as well. This test is not a boolean test. Without any operators, it just tests for the presence of a word. 1 is a word. 0 is a word. Both evaluate as truewww.unixbabuforum.inF3 is global, so in all cases, once F3 is initialised, it's value is 6. Before the F3=6 line, it is not the case. It would be good to initialise it at the beginning of your script (it's clean). 

To obtain what you want (that is f2() not knowing the X from f1() and also main() not knowing 
the value of X, you must choose ksh (actually ksh93, mine is ksh93t+) and use the syntax 
function f1 { ... } and not the syntax f1() { ... } 
and typeset X (the local keyword doesn't exist in ksh). 

For bash, the f1() and function f1 syntaxes don't change anything (AFAIK) 
For ksh93, there are a lot of differences, this static scope one is interesting. 

Note also that in ksh93 with the function f syntax, if you initialize X in main, you will see the "local/typeset" X in f1, and the global X in f2, whilst with the f() syntax, typeset or not, once X is initialised, it's known everywhere www.unixbabuforum.inlocal variables are visible to functions called by the parent function. Since f2() is called by f1(), any local variables defined in f1() will be visible to f2(). 
The variable F3, however, is not declared as local, so it is visible globally throughout the script.


Post a Comment

Design by BABU | Dedicated to grandfather | welcome to BABU-UNIX-FORUM