Computing.Net > Forums > Unix > Variable Variables

Variable Variables

Reply to Message Icon

Original Message
Name: jakekatz
Date: December 4, 2007 at 09:32:58 Pacific
Subject: Variable Variables
OS: Solaris 10 Update #4
CPU/Ram: Sparc
Model/Manufacturer: Sun SunBlade 1500
Comment:

How to create a variable partially from another variable. Can it be done?

I'm trying to do this;

for X in A B; do
Site_${X}="Value of $X"
done

bash: Site_A=Value of A: command not found
bash: Site_B=Value of B: command not found

I would like the variables Site_A & Site_B to contain some values.

Any ideas?


Report Offensive Message For Removal


Response Number 1
Name: James Boothe
Date: December 4, 2007 at 10:05:42 Pacific
Subject: Variable Variables
Reply: (edit)

Since your variable name includes a variable, the shell needs to parse (evaluate) the variable assignment line twice.  And to prevent the shell from removing the double-quotes on the initial evaluation (which would cause a syntax error), I protect them with back-slashes.

for X in A B; do
eval Site_${X}=\"Value of $X\"
done

echo $Site_A
Value of A
echo $Site_B
Value of B

So the line to be processed by the shell is:
eval Site_${X}=\"Value of $X\"

After the initial processing by the shell, we now have:
eval Site_A="Value of A"

Then the eval command causes the result to be processed again:
Site_A="Value of A"


Report Offensive Follow Up For Removal

Response Number 2
Name: jakekatz
Date: December 4, 2007 at 11:13:55 Pacific
Subject: Variable Variables
Reply: (edit)

That's it!

I must learn the value of the 'eval' command :)

Thank you ever so much.

Jake.


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Variable Variables

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software