variable of Variable

拥有回忆 提交于 2019-12-10 20:57:28

问题


I have to print a variable value which is art variable. eg. variables are

A = X
Z_X = Test

Set in shell using

setenv A X
setenv Z_X Test

I want to print $Z_X value using $A

I am trying but without any success.

echo ${Z_${A}}
echo ${Z_[$A]}

could anyone tell me where I am wrong.

regards


回答1:


A = X
Z_X = Test

This seems wrong; in csh, you need to use the set keyword to assign variables; in addition, the convention is also to use lower case for "normal" variables, and UPPER CASE for environment variables:

set a = x
set z_x = Test

You can then use eval to get what you want:

% eval echo \$z_$a
Test

% set x = `eval echo \$z_$a`
% echo $s
Test

This may be dangerous if you don't trust the source of $a, since it may also do a rm -rf / or something similarly dangerous (but if you trust the source of $a, it's perfectly fine).

You can get a list of all variables with set:

% set | grep ^z_$a
z_x     Test

% set | grep ^z_$a | awk '{print $1}'
z_x

Which is the only safe way I can figure out to do what you want.




回答2:


Generally this is a bad idea, and you should rather rethink your approach.

  • You can use indirect expansion:

    name=Z_$A
    echo ${!name}
    

    From the manual:

    If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

  • Or indirect references:

    name=Z_$A
    eval echo \$$name
    

    You can find more about indirect references in the guide.



来源:https://stackoverflow.com/questions/27604063/variable-of-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!