请考虑以下脚本(用于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
Run Code Online (Sandbox Code Playgroud)
运行时,它会产生以下输出:
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
Run Code Online (Sandbox Code Playgroud)
(这不是预期的!)
如果我在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
Run Code Online (Sandbox Code Playgroud)
(这是预期的!)
这是一个奇怪的ksh93.
typeset将变量定义为local的变量仅适用于函数定义样式:
function func_name
{
}
Run Code Online (Sandbox Code Playgroud)
不是功能定义样式:
func_name()
{
}
Run Code Online (Sandbox Code Playgroud)
随着func_name()风格,一切都是全球性的.所以行为ksh就像预期的那样!
但bash显然比ksh这方面更安全.因此,它将两个函数中的变量范围设置typeset为使用时的本地.
在ksh文档中有FAQ条目,说明函数定义之间的区别:
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1254 次 |
| 最近记录: |