【问题标题】:How to echo the name of the argument but not its value如何回显参数的名称而不是其值
【发布时间】:2014-02-22 13:07:13
【问题描述】:

简单功能:

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 个参数实例,一个用于它们的值,另一个用于它们的命名?

【问题讨论】:

    标签: bash function arguments


    【解决方案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 内置函数相同的名称。 test 内置的 shell - 因此在第一个版本中我将其称为 xtest

    【讨论】:

    • Cn_add 是一个普通命令,而不是脚本 :( 所以我需要这个:test=5,echo $test(产生 5),但我需要一个产生“test”的命令,而不是它的值..
    • @aprin 我完全按照您的要求回答了一个问题...如果您的需求不同,请重新编辑您的问题...
    • 天啊,我一开始没有注意到 cmets...你是对的...不过放松! :)) 非常感谢!!!
    • @aprin 很高兴为您提供帮助 - 享受 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多