You are not logged in.

#1 2011-04-30 15:06:11

tri1976
Member
Registered: 2009-09-07
Posts: 152

bash set variable for a variable [SOLVED]

For example, i=$VAR and VAR="SOMEVAL", then I want to set the value of $i to 1 (so echo $SOMEVAL, give me 1).  Is there a way to this?

Last edited by tri1976 (2011-04-30 15:47:45)

Offline

#2 2011-04-30 15:29:17

Procyon
Member
Registered: 2008-05-07
Posts: 1,819

Re: bash set variable for a variable [SOLVED]

It's called indirect reference.

i=VAR
VAR=nothing

printf -v $i 1
echo ${!i} #<-- 1
echo $i #<-- VAR
echo $VAR #<-- 1

Normally printf -v VARIABLE works without $, with the $ you assign to VARIABLE's content.

You can assign using multiple variables, but you can't retrieve it without 1 single variable. Example:

VAR=nothing

e=VA
f=R

printf -v $e$f 2
echo ${!$e$f} #<-- nothing (no combination works)
temp=$e$f
echo ${!temp} #<-- 2

#alternatively
eval echo \$$e$f #<-- 2 (but eval doesn't work very well in complex code, like array assignment etc etc)

Offline

#3 2011-04-30 15:47:13

tri1976
Member
Registered: 2009-09-07
Posts: 152

Re: bash set variable for a variable [SOLVED]

@Procyon, thanks for the tip.

Offline

Board footer

Powered by FluxBB