Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable of Variable

Tags:

shell

unix

echo

csh

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

like image 710
user1495523 Avatar asked Jan 28 '26 15:01

user1495523


1 Answers

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.

like image 94
Martin Tournoij Avatar answered Jan 31 '26 15:01

Martin Tournoij



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!