2012-06-08 48 views
2

在bash中有一種方法可以理解傳遞給它的變量的名稱?在bash中傳遞給函數的變量的名稱

例子:

var1=file1.txt 
err_var=errorfile.txt 

function func1 { 
    echo "func1: name of the variable is: " $1 
    echo "func1: value of variable is: " $1 
    echo 
    if [ ! -e $var1 ] 
    then 
     $1 = $err_val #is this even possible? 
    fi 
    func2 $1 
} 

function func2 { 
    echo "func2: name of the variable is: " $1 
    echo "func2: value of variable is: " $1 
    echo 
} 

func1 $var1 
func1 $err_var 

我希望如果FILE1.TXT的存在是爲了得到以下的輸出:

func1: name of the variable is: var1 
func1: value of variable is: file1.txt 

func2: name of the variable is: var1 
func2: value of variable is: file1.txt 

當FILE1.TXT不存在:

func1: name of the variable is: var1 
func1: value of variable is: file1.txt 

func2: name of the variable is: err_var 
func2: value of variable is: errorfile.txt 

有任何想法嗎?

+0

如果你做了'FUNC1 「富」'? –

+0

'-e'測試文件是否存在,而不是變量存在(或(非)空洞)。 –

回答

9

不,變量在函數看到它之前展開。該函數只能看到該值,而不是變量名。

如果您通過變量名稱unexpanded而沒有美元符號,則可以使用間接方式。

get_it() { 
    echo "${!1}" 
} 

演示:

$ foo=bar 
$ baz=qux 
$ get_it foo 
bar 
$ get_it baz 
qux 
+0

謝謝丹尼斯。是否有可能在沒有靜態定義變量的情況下在函數中設置變量?即調用get_it foo並通過執行類似於get_it(){$ 1 = foosomething echo「$ {!1}」}來設置foo = somethingelse的函數。} – jared

+0

@jared:您可以使用'declare',但會自動使變量局部。你可以使用'export',但是很明顯這個變量會把變量導出到任何子進程(這可能是不希望的)。 'set_it(){export「$ 1」=「something_else」; };條= one_thing; set_it欄; get_it欄# –

+0

您也可以使用'eval'。請參閱https://stackoverflow.com/questions/9714902/how-to-use-a-variables-value-as-other-variables-name-in-bash – Fabio

相關問題