2011-04-11 85 views
1

我想調用函數「B」並傳遞給它將調用的另一個函數名稱(A1,A2等)。在這個函數中,通過哪個名字,我初始化了幾個變量,但是我不能從「B」函數中讀取它們。當函數被撤銷時,Bash全局變量沒有改變

function A1 
{ 
    echo "func 1" 
    result1="a1" 
    return 0 
} 

function A2 
{ 
    echo "func 2" 
    anotherResult="a2" 
    #..some other initialization 
    return 0 
} 
#... 

function B 
{ 
    output=`$1` # $1 - function name 
    echo output=$output 
    echo result1=$result1 # <--- ERROR! result1 is empty! 
} 

B "A1" # main script runs function B and passes other function name 
+0

output ='$ 1'帶反引號,沒有反斜槓 – 2011-04-11 13:35:16

+0

和B「A1」最後也是bash代碼 – 2011-04-11 13:37:25

+0

據此編輯。 – mouviciel 2011-04-11 14:23:48

回答

4

您的功能B不會調用A1。

請注意,output=$($1)不會做你所期望的,因爲$(...)裏面運行的任何內容都將在不同的進程中執行,當這個進程終止時,你設置的值將不再可用。

所以:

function B 
{ 
    output=\`$1\` # <-- this will not call the $1 but will only print it 

    output=`$1` # <-- ($($1) is a better style) - will call whatever 
        #  inside $1, but in another process 

    $1   # <-- here is the missing call in the current process. 
    ... 
} 

您可以使用重定向例如A1 > tmpfile文件或命名管道,在通過文件系統的輸出來獲得,同時保持在當前進程的副作用:

function B 
{ 
    $1 > tempfile 
    read output < tempfile 

    echo output=$output 
    echo result1=$result1 
} 

會做你所期望的,但是會使用tempfile你的文件 - 系統。

+0

我需要該函數寫入 output = func 1 result1 = a1 – 2011-04-11 13:48:29

+0

當我調用output = \'$ 1 \'時 - 變量輸出被初始化,但result1不是。 – 2011-04-11 13:51:02

+0

而且我無法兩次調用我的函數$ 1,因爲它運行了大約一分鐘。 – 2011-04-11 13:55:32