Consider the following script (arithmetic syntax that is used for local_var2 is irrelevant for this case):
#!/bin/ksh
function my_func1
{
typeset local_var1=one
typeset local_var2
(( local_var2 = 1 ))
echo my_func1: local_var1 = $local_var1, local_var2 = $local_var2
}
my_func2()
{
typeset local_var1=two
typeset local_var2
(( local_var2 = 2 ))
echo my_func2: local_var1 = $local_var1, local_var2 = $local_var2
}
local_var1=0
local_var2=0
echo before functions: local_var1 = $local_var1, local_var2 = $local_var2
my_func1
echo after my_func1: local_var1 = $local_var1, local_var2 = $local_var2
my_func2
echo after my_func2: local_var1 = $local_var1, local_var2 = $local_var2
When run it produces the following output:
before functions: local_var1 = 0, local_var2 = 0
my_func1: local_var1 = one, local_var2 = 1
after my_func1: local_var1 = 0, local_var2 = 0
my_func2: local_var1 = two, local_var2 = 2
after my_func2: local_var1 = two, local_var2 = 2
(which is not what is expected!)
If I run the same script in bash, the output is:
before functions: local_var1 = 0, local_var2 = 0
my_func1: local_var1 = one, local_var2 = 1
after my_func1: local_var1 = 0, local_var2 = 0
my_func2: local_var1 = two, local_var2 = 2
after my_func2: local_var1 = 0, local_var2 = 0
(which is what is expected!)
This is one of the weirdness of ksh93
.
typeset
ting of variables to define their scope as local only works with the function definition style:
function func_name
{
}
Not with the function definition style:
func_name()
{
}
With the func_name()
style, everything is global. So the behaviour of ksh
is as expected!!!
But bash
is clearly saner than ksh
in this regard. So it sets the scope of variables in both functions as local when typeset
was used.
There's FAQ entry in ksh documentation stating the difference between the function defintions:
Q18. What is the difference between function name and name()?
A18. In ksh88 these were the same. However, the POSIX standard
choose foo() for functions and defined System V Release 2
semantics to them so that there are no local variables
and so that traps are not scoped. ksh93 keeps the ksh88
semantics for functions defined as function name, and
has changed the name() semantics to match the POSIX
semantics. Clearly, function name is more useful.
Based on the description in this answer, you are most likely running the AT&T version of ksh
, for which the typeset
built-in makes variables local only in functions declared with the function
keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With