1832552 Members
6429 Online
110043 Solutions
New Discussion

${X_${Y}}

 
Praveen Bezawada
Respected Contributor

${X_${Y}}

Hi
In shell can we do something of the kind

${X_${Y}} to print the value of X_2 when $Y=2

8 REPLIES 8
James R. Ferguson
Acclaimed Contributor

Re: ${X_${Y}}

Hi Praveen:

While this seems intuitive. I don't think this will work. From the 'sh-posix' man pages in the parameter substitution discussion you can note: "The shell reads all the characters from ${ to the matching } as part of the same word, even if it contains braces or metacharacters."

Regards!

...JRF...

Satish Y
Trusted Contributor

Re: ${X_${Y}}

No, it is not possible.

Cheers...
Satish.
Difference between good and the best is only a little effort
James R. Ferguson
Acclaimed Contributor

Re: ${X_${Y}}

Hi Praveen:

Another comment: You could consider setting and referencing your variables in an array.

...JRF...
A. Clay Stephenson
Acclaimed Contributor

Re: ${X_${Y}}

Hi Praveen:

One other option you have is to set up associative arrays in awk so that your values are no referenced by numerical values but rather by strings such as "X1","X2","red","Blue".

Regards, Clay
If it ain't broke, I can fix that.
Frank Li
Trusted Contributor

Re: ${X_${Y}}

Why not use $X_$Y or $X_${Y} directly ?

The shell will try its best to explain the variable !
Hi Friend
Curtis Larson
Trusted Contributor

Re: ${X_${Y}}

what you need to use is "eval"

eval print \"\$X_$Y\"

sometimes it is easier not to mess with the quotes and do something like

eval z=\$X_$Y
print $z
Magdi KAMAL
Respected Contributor

Re: ${X_${Y}}

Hi Praveen,

Try the following , it works :

echo ${X}_${Y}

Magdi
Carlos Fernandez Riera
Honored Contributor

Re: ${X_${Y}}

Arrays in shell:

set -A x

x[1]=jjjjjj
x[2]=yyyyyy

y=2

echo ${x[$y]}


unsupported