Translate

Image of Android Wireless Application Development
Image of Modern Operating Systems (3rd Edition)
Image of Linux Kernel Development (3rd Edition)
Image of XSLT 2.0 and XPath 2.0 Programmer's Reference (Programmer to Programmer)

Differences in Variable Scope in Shell Functions

Ksh93 and bash have subtly different scopes for variables defined in shell functions as the following example shows:

# POSIX function syntax
testme2()
{
   printf "Function testme2 invokedn"
   var21=testme21
   typeset var22=testme22

}

function testme1
{
   printf "Function testme1 invokedn"
   var11=testme11
   typeset var12=testme12
}

testme1
echo "VAR11=$var11"
echo "VAR12=$var12"


Here is the output when run under ksh93:

Function testme1 invoked
VAR11=testme11
VAR12=
Function testme2 invoked
VAR21=testme21
VAR22=testme22


and here is the output when run under bash:

Function testme1 invoked
VAR11=testme11
VAR12=
Function testme2 invoked
VAR21=testme21
VAR22=


Note the different output for var22!

Ksh93 has lexical scoping. A variable is normally global to the shell it is defined in from the time it is defined. However the typeset command can be used to make it local to the function the variable is defined in. Bash has subtly different scoping rules.

Beware, the difference in variable scoping can bite you hard when porting shell scripts to different environments.

Comments are closed.