LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   SH: Recursive Variable Substitution (https://www.linuxquestions.org/questions/programming-9/sh-recursive-variable-substitution-817387/)

TVT 07-01-2010 07:41 AM

SH: Recursive Variable Substitution
 
Hi!

I have the following test code fragment:

Code:

#! /bin/sh

A1='ZZZ'

B='A'
N='1'

if [ "${$B$N}" == 'ZZZ' ]; then echo 'OK'; fi

When I try to run it 'sh' reports the following message^

Code:

test.sh: ${$B...}: Bad substitution
You might understand what I mean with that test code so could you recommend how to achieve the required effect?

Guttorm 07-01-2010 08:49 AM

Hmm. I think you are looking for eval.

Code:

A1="ZZZ"
V1="A"
V2="1"
VARNAME="$V1$V2"
eval VALUE=\$$VARNAME
echo $VALUE


TVT 07-01-2010 09:21 AM

Quote:

Originally Posted by Guttorm (Post 4020537)
Hmm. I think you are looking for eval.

Code:

A1="ZZZ"
V1="A"
V2="1"
VARNAME="$V1$V2"
eval VALUE=\$$VARNAME
echo $VALUE


YES but how to elegantly use your way with 'if' statement?

grail 07-01-2010 09:27 AM

You could possibly go one line less too:
Code:

A1="ZZZ"
V1="A"
V2="1"
eval VARNAME="$V1$V2"
echo ${!VARNAME}

Just an alternative at the end their for indirect

Edit: Use the "if" instead of "echo" line

TVT 07-01-2010 12:57 PM

Quote:

Originally Posted by grail (Post 4020582)
You could possibly go one line less too:
Code:

A1="ZZZ"
V1="A"
V2="1"
eval VARNAME="$V1$V2"
echo ${!VARNAME}

Just an alternative at the end their for indirect

Edit: Use the "if" instead of "echo" line

Doesn't seem to solve the difficulty:
Code:

$ sh -x test1.sh
+ A1=ZZZ
+ V1=A
+ V2=1
+ eval VARNAME=A1
+ VARNAME=A1
test1.sh: ${!V...}: Bad substitution


unSpawn 07-01-2010 01:35 PM

Quote:

Originally Posted by TVT (Post 4020836)
Doesn't seem to solve the difficulty

Is your shell by any chance a "true" Bourne Shell?

TVT 07-01-2010 03:09 PM

Quote:

Originally Posted by unSpawn (Post 4020875)
Is your shell by any chance a "true" Bourne Shell?

No. My shell is just ordinary /bin/sh shell (see message title). This is because some systems do not have bash by default.

tuxdev 07-01-2010 03:30 PM

Quote:

No. My shell is just ordinary /bin/sh shell (see message title). This is because some systems do not have bash by default.
Just because it's /bin/sh doesn't give *any* information on whether it's a actual legacy Bourne shell or a POSIX shell. Please verify that it really is POSIX, not Bourne.


All times are GMT -5. The time now is 04:49 AM.