Calling a Variable based on a Variable

Hi all,

I have a source config file with variables like so:

eth1_ip=192.168.1.99
eth2_ip=192.168.1.123
eth3_ip=172.16.1.1

I am trying to run a script which loops based on the number of eth interfaces on a machine and therefore modifies the variable it calls in the environment based on the interface in each loop:

source config.conf
for int in `ip link |grep eth[0-7] |cut -d " " -f 2|cut -d":" -f1`; do

echo $int_ip

done

Any ideas??

thanks,Ll

links=$(ip link |grep eth[0-7] |cut -d " " -f 2|cut -d":" -f1` | tr -s '\n' ' ')
for i in $links
do
  echo $i
done

Is that what you are asking -- not clear to me, so I guessed. The cut and chop probably should be replaced with an awk call.

links=$(ip link |grep eth[0-7] | awk -F '[ :]' '{printf("%s ", $3)}')
1 Like

That is what the current code does.
But I need it to source the variables from config.conf being;

eth1_ip=192.168.1.99
eth2_ip=192.168.1.123
eth3_ip=172.16.1.1

And re-write the variable from the config file so that it will echo;

192.168.1.99
192.168.1.123 
172.16.1.1

for variables;

eth1_ip
eth2_ip
eth3_ip

so the statement needs to look something like;

echo $($int"_ip")

But the above statement is only my guess.

---------- Post updated 06-06-13 at 12:17 AM ---------- Previous update was 05-06-13 at 12:58 PM ----------

Ok I have cracked it:

# config.conf
eth1_ip=192.168.1.1
source config.conf
for int in `ip link |grep eth[0-7] |cut -d " " -f 2|cut -d":" -f1`; do

ethip=$"$int"_ip

echo ${!ethip}        # This gives the output I was looking for.

done
1 Like

Thanks for informing us !

Note that ${! ... } is a bashism and does not work in other shells.

A more portable method is to use eval, i.e.

eth1_ip=192.168.1.1
int=eth1

ethip=$"$int"_ip
eval echo \$${ethip}

Or better yet, just use an array. Dynamic variable names are seldom a good idea. You can get the length of an array, for instance, but cannot easily tell how many eth? variables you have.