tags:

views:

63

answers:

5

How can I retrieve the variable value if I have variable name as string?

var1="this is the real value"
a="var1"
Do something to get value of var1 just using variable a.
Thanks.
So here is the actual problem: I have some AMI's (Amazon Machine Image) and I want to fire few instances of each AMI. As soon as booting is complete, I want to setup each instance according to its AMI type. And I don't want to bake lots of scripts or secret keys inside any AMI. So I prepare a startup script which is quite general for my purpose and I put it on S3 (publicly accessible link). And in rc.local I put small piece of code which fetches startup script and executes it (This is all I have in AMIs). Then there is a common configuration script which is applicable for all AMIs and special setup scripts for each AMI. All these scripts are again on S3 but they are private i.e. one needs a signed URL to access those.
So now when I fire an instance of AMI (my_private_ami_1), I pass a signed URL for one more file presented on S3 which contains signed URL for all private scripts in terms of key/value pair.
config_url="http://s3.amazo.../config?signature"
my_private_ami_1="http://s3.amazo.../ami_1?signature"
...
So when startup script runs, it downloads the above file and source it then it checks for its AMI type and then it needs to pickup the correct setup script for itself.

ami_type=GET AMI TYPE #ex: sets ami_type to my_private_ami_1
setup_url=GET THE SETUP FILE URL BASED ON AMI_TYPE # this is where this problem arises
. So now I can have a generic code which can fire instances irrespective of their AMI types. And instances can take care of themselves.

+1  A: 

Modified my search keywords and Got it :).

eval a=\$$a
Thanks for your time.

bhups
+4  A: 

You can use ${!a}.

Phil Ross
A: 

Why do you want to do this? Could you show us some real code?

It might be a bad idea, and it's possible that there might be a better solution for your actual use case.

Christoffer Hammarström
It's called indirection, and is a useful and powerful programming tool.
anon
its useful and dangerous too. The cleaner way is to use arrays (or associative arrays)
I've edited the problem statement with actual problem.
bhups
+1  A: 
X=foo
Y=X
eval "Z=\$$Y"

sets Z to "foo"

anon
A: 

modern shells already support arrays( and even associative arrays). So please do use them, and use less of eval.

var1="this is the real value"
array=("$var1")
# or array[0]="$var1"

then when you want to call it , echo ${array[0]}