2014-02-22 18 views
1

简单的函数:如何呼应参数的名称,但不是它的价值

arg1=5 
arg2=10 

test(){ 
    cn_add $1  
    cn_add $2 
    echo "$1 $2" <--this is where my problem is 
} 

而且我想下面的输出:

test arg1 arg2 outputs: 
add 5 to cn 
OK 
adding 10 to cn 
OK 
arg1 arg2 

怎样才可以有自变量2分的情况下,一个为他们的价值,另一个为他们的命名?

回答

1

也许吧?

#You can remove this up to #/remove - it is only for testing 
cn_add() { 
    echo add $1 to cn && echo OK 
} 
#/remove 

test(){ 
    cn_add ${!1}  #evaluate the variable what's name is in $1 
    cn_add ${!2} 
    echo "$1 $2" #this is where my problem was 
} 

arg1=5 
arg2=10 

test arg1 arg2 #call with the name of variable (not with a value like $arg1) 

生产:

add 5 to cn 
OK 
add 10 to cn 
OK 
arg1 arg2 

${!1}被称为indirect variable

一个评论:

通常一个好的做法名称与同名的壳壳功能内建命令。 test shell内置 - 因此在第一个版本中,我称它为xtest

+0

Cn_add是正常的命令,而不是脚本:( 所以我需要这样的:测试= 5,回声$测试(产生5),但我需要产生“测试”的命令,而不是其值.. – aprin

+0

@ aprin我回答了一个问题,正如你问的那样...如果你的需求不同,请重新编辑你的问题... – jm666

+0

哎呀,我没有注意到开始时的意见... 你是对的...... .relax虽然!:))非常感谢你! – aprin

相关问题