2012-06-08 46 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

相关问题