Bash indirect variable referencing

前端 未结 1 939
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 15:44
foo=\'abc\'
bar=\'xyz\'
var=bar

How to I get access to \'xyz\' when I have var?

I\'ve tried:

$(ec         


        
相关标签:
1条回答
  • 2020-12-03 16:28

    Use bash indirect variable reference:

    ${!var}
    

    And of course can be done with eval, not recommended:

    eval 'echo $'"$var"
    

    Why:

    $ bar=xyz
    
    $ var='bar;whoami'
    
    $ eval 'echo $'"$var"
    xyz
    spamegg
    

    Th command whoami is being evaluated too as part of evaluation by eval, imagine a destructive command instead of whoami.


    Example:

    $ bar='xyz'
    
    $ var=bar
    
    $ echo "${!var}"
    xyz
    
    $ eval 'echo $'"$var"
    xyz
    
    0 讨论(0)
提交回复
热议问题