简体   繁体   中英

Can I reference an existing bash variable by joining variables together?

I've defined a variable say:

bob_pants="fancy"

and now I want to reference the contents of $bobs_pants by using another variable.

name="bob"
item="pants"

Can I do something like:

echo "${name} has ${name}_${item} ${item}"

I want the output for the above to be "user bob has fancy pants" So far I've only succeeded in getting "user bob has bob_pants pants"

I guess I need some way for ${name}_${item} to be seen as ${bob_pants} but all the ways I tried to group the variables into one haven't worked.

In bash :

bob_pants="fancy"
name="bob"
item="pants"
var="${name}_${item}"
echo "${name} has ${!var} ${item}"

The ${!var} notation evaluates to the variable named by $var . However, you can't do:

echo "${name} has ${!${name}_${item}} ${item}"

Check out eval :

$ x=bob  
$ y=pants  
$ echo $x\_$y  
bob_pants  
$ eval echo \$$x\_$y  
fancy
$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM