考虑以下脚本(用于 local_var2 的算术语法对此案例无关):
#!/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
运行后将生成以下输出:
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
(这并不是预期的结果!)
如果我在bash中运行相同的脚本,输出为:
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
(这是预期的结果!)
set -vx
(并根据Shell选择每个函数),您将看到变量内容在第二次调用时与预期明显不同。 - NeronLeVelu