variable of Variable

2019-07-24 14:01发布

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

2条回答
Evening l夕情丶
2楼-- · 2019-07-24 14:31

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.

查看更多
仙女界的扛把子
3楼-- · 2019-07-24 14:33

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.

查看更多
登录 后发表回答