2

I have a small script with the following lines

echo mom,dad |awk -F, '{print $1,$2}' | while read VAR1 VAR2
do
 for i in VAR1 VAR2
  do
   eval X=\$$i
   echo $X
 done  
done

OUTPUT:

mom
dad

What is this line doing eval X=\$$i?

I understand the rest of the lines, but I don't understand the iterations of this for loop with eval. Can someone shed light on this ? I am using Solaris 5.10 with Korn Shell.

4
  • 1
    Jeff Schaller has a good explanation of what's going on. It's possible to get this same effect without eval by replacing the eval line with X=${!i} which will assign to X the value of the variable whose name is stored in i Commented Sep 15, 2015 at 0:09
  • @EricRenouf Thanks.How does X=${!i} work, can you break it down little further ? Commented Sep 15, 2015 at 2:03
  • ${} is a general syntax for accessing a variable (though it can often be shortened to $varname). You can do many things within the {} to affect the variable access, one of which is if the first character in {} is ! the rest is another variable name (i in this example) then the value in that other variable (i) will be expanded and treated as the name of the variable to access with the ${}, so if i=VAR1 then ${!i} becomes ${VAR1} which is the same as $VAR1 Commented Sep 15, 2015 at 2:09
  • @EricRenouf Thank you..makes more sense now. Commented Sep 15, 2015 at 2:14

1 Answer 1

11

eval performs an extra level of substitution and processing on the remainder of the line.

In the first iteration of the loop, i is set to "VAR1", and one level of backslash-escaping is reduced, so:

eval X=\$$i

becomes:

X=$VAR1

which evaluates to:

X=mom

(repeat for the next loop, only $i is then VAR2, and $VAR2=dad)

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.