簡體   English   中英

ksh和bash腳本之間的區別

[英]Difference between ksh and bash script

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

(這是預期的!)

這是ksh93一個奇怪之ksh93

typeset變量以將其范圍定義為local僅適用於函數定義樣式:

function func_name
{
}

不是功能定義樣式:

func_name()
{
}

使用func_name()樣式,一切都是全局的。 所以ksh的行為正如預期的那樣!

但在這方面, bash顯然比ksh健全。 因此,當使用typeset時,它將兩個函數中的變量范圍設置為local。

在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.

基於在說明這個答案 ,你最有可能運行AT&T版ksh ,為此, typeset內置使得本地只能與聲明的函數變量function的關鍵字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM