差分

2014-05-08 25 views
9

考慮以下腳本(即用於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 

(這是預期!)

+1

測試並確認輸出!雖然,除了說ksh糟糕之外,我沒有對此的解釋;-) – zmo

+0

在代碼中有一個'set -vx'(並且每個函數都依賴於shell),你會發現varible的內容顯然與預期的不同首先使用第二個電話 – NeronLeVelu

回答

7

這是ksh93的怪事之一。

typeset變量婷界定其範圍爲本地只能與函數定義風格的作品:

function func_name 
{ 
} 

不能與函數定義風格:

func_name() 
{ 
} 

隨着func_name()風格,一切都全球。所以ksh的行爲如預期的那樣!

但在這方面bash顯然比ksh更清晰。因此,當使用typeset時,它將這兩個函數中的變量範圍設置爲本地。

FAQ進入KSH文件中寫明功能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. 
+1

+1進行啓發 – PradyJord

2

基於對this answer的描述,你是最有可能運行的ksh的AT & T版,爲其typeset建-in僅在用function關鍵字聲明的函數中使變量局部變量