0

I'd like to know how to print variable value when I know the name of variable. I need a little help to put all the pieces together.

Let say I have a=A and b=B. Additionally I have list of a and b in file. And I want to print

a=A
b=B

I was testing with eval, but I wasn't not able to do it in a for loop. I guess because I'm not able to capture the result of eval...

which I can put together like this, but it smells...

setup

$ cat f.txt
a
b
$ a=A
$ b=B

execution

for n in `cat f.txt`
do
    echo -n $n
    eval echo \$$n
done

and wanted result is

a=A
b=B

but if I need to use the values later it won't work...

What I'm not able to do is

val=`eval echo \$$n`

to be able to do echo $val later.

Betlista
  • 10,327
  • 13
  • 69
  • 110
  • You really want to read http://mywiki.wooledge.org/DontReadLinesWithFor and [When to wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Aug 31 '17 at 13:14
  • Thanks for the links, but I just wanted to keep it simple... – Betlista Aug 31 '17 at 13:18
  • It's not more complicated to do it correctly. – tripleee Aug 31 '17 at 13:19
  • It is correct for what I need, it is just not robust enough for all the case one can imagine, but I just wanted to focus on a problem... – Betlista Aug 31 '17 at 13:23

2 Answers2

1

How about this?

$ for n in `cat f.txt `; do 
>   val=$(eval "echo \$$n")
>   echo $n=$val
> done
a=A
b=B

Of course you don't need to use any additional variable (val), and it might look like:

$ for n in $(cat f.txt); do echo $n=$(eval "echo \$$n"); done
a=A
b=B
gbajson
  • 1,531
  • 13
  • 32
  • Thanks, that's it, when I was trying I didn't have it in quotes - `$(eval echo \$$n)`, maybe that's what @tripleee wanted to tell me... – Betlista Aug 31 '17 at 13:28
0

You can do:

$ a=A
$ echo $a
A
$ echo a=$a
a=A
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • No, you are working with `a` directly, but I have the name in other variable - `n` in example above... – Betlista Aug 31 '17 at 13:19