[ale] for in bash using eval

David S. Jackson dsj at dsj.net
Wed Sep 2 18:00:51 EDT 1998


Hi Matt, et al,

Thanks for the prompt reply and helpful info.

I don't know whether any of you have the fishbook handy, but there
appears to be a special control structure the author is looking for
that derives from the for loop.  The examples you, Matt, provided are
cool, but I don't think they're quite what the guy is looking for.
It's exercise 3a-b on page 187 (end of Chapter 7).

In case you don't have the fishbook handy, allow me to quote:

<quote>

3. Here are some problems that really test your knowledge of eval and
the shell's command-line processing rules.  Solve these and you're a
true bash hacker!

a.  Advanced shell programmers sometimes use a little trick that
includes eval: using the value of a variable as the name of another
variable.  In other words, you can give a shell script control over
the names of variables to which it assigns values.  How would you do
this? 

(Hint: if $object equals "person" and $person is "alice", then you
might think that you could type echo $$object and get the response
alice.  This doesn't actually work, but it's on the right track.)

b.  You could use the above technique together with other eval tricks
to implement new control structures for the shell.  For example, see
if you can write a script that emulates the behavior of a for loop in
a conventional language like C or Pascal, ie a loop that iterates a
fixed number of times, with a loop variable that steps from 1 to the
number of iterations (or, for C fans, 0 to iterations-1).  Call your
script loop to avoid clashes with the keywords for and do.

</quote>


So, that's it.  The "a" part of the problem I came up with was as
follows:

----cut--------

#! /bin/sh

person=alice
object=$person

eval "echo $object"

----cut--------


I guess he means I'm supposed to turn this into a control structure
somehow, but I don't get it.  If I were using a control number, I
would think it most likely to use something like:

----cut----

#! /bin/sh

echo -e "\nEnter a number, any number: "
read tempnum

count=1

while [ $tempnum -ge $count ]; do
	echo $count
	count=(($count+1))
done

----cut----



Can anyone guess what the authors of the fishbook are talking about
here for assignment "b"?



--
David S. Jackson                           http://www.dsj.net
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Your mouse has moved. Please wait while Windows reboots so the 
change can take effect.






More information about the Ale mailing list