简单功能:
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个参数实例,一个用于它们的值,另一个用于命名?
答案 0 :(得分: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
一条评论:
通常不一个好的做法,命名shell函数与shell builtins同名。 test
是内置的shell - 因此在第一个版本中,我将其称为xtest
。