You are not logged in.

#1 2010-04-19 19:03:26

haxor
Member
Registered: 2010-04-19
Posts: 1

Bash var within a varname

Hi im having this problem with some varnames..
the thing is: i've set a bunch of variables from a file splitting it into a new var at each newline. it uses a couner at the end
the code i use for setting the var is as following

exec 3< filename
   while read <&3
      do echo "$REPLY" > /dev/NULL
      export VAR$COUNTER="$REPLY"
      COUNTER=`echo $COUNTER + 1 | bc`
   done
exec 3>&-

The problem i'm having is that when (a bunch of code later) i need these vars the seem not so usefull...

$COUNTER=3
for i in `seq 1 $COUNTER`;
  do
    echo "saving output"
    echo "$VAR$i"
  done

i thought this code would result into the following

echo $VAR1
echo $VAR2
echo $VAR3

instead all the code outputs is

1
2
3

I know it's looking for $VAR who doesn't exist
but how can i fix it, what am i doing wrong??

Thanks in advance

Offline

#2 2010-04-19 19:11:40

Busata
Member
From: Belgium
Registered: 2010-04-04
Posts: 30
Website

Re: Bash var within a varname

are you sure you're not looking for arrays? http://tldp.org/LDP/abs/html/arrays.html

Offline

#3 2010-04-19 19:12:52

davvil
Member
Registered: 2008-05-06
Posts: 165

Re: Bash var within a varname

You can use eval. For setting the variables:

eval export VAR$COUNTER="$REPLY"

(as a side note, do you need to export the variable?)

And for getting the value:

eval echo \$VAR$i

Or yes, use arrays, as Busata suggests.

Last edited by davvil (2010-04-19 19:13:40)

Offline

#4 2010-04-21 16:53:06

delerious010
Member
From: Montreal
Registered: 2008-10-07
Posts: 72

Re: Bash var within a varname

set a dynamically named variable : eval varname$i=$value
retrieve a dynamically named variable : ${!varname$i}

Offline

#5 2010-04-25 13:21:43

Profjim
Member
From: NYC
Registered: 2008-03-24
Posts: 658

Re: Bash var within a varname

Also you want /dev/null, not /dev/NULL

Offline

Board footer

Powered by FluxBB