sh loop variable and "double indirection"
Kris Stephens [Hail Eris!]
krs at uts.amdahl.com
Mon Jan 28 15:09:16 AEST 1991
In article <1991Jan27.044258.18779 at shibaya.lonestar.org> afc at shibaya.lonestar.org (Augustine Cano) writes:
>I am trying to specify (at run time) an upper limit for a loop in a shell
>script. In pseudo-code the ideal would be something like this:
>
>read i
>for 0 to i
>do
>...
>done
Let me give you the ksh version first, then the (slower) sh mods -- it's
slower because each iteration requires a fork/exec not required in ksh.
:
# ksh version
# (note -- in commentary, Augustine requests that we stop at i-1)
typeset -i i j # make things run faster by naming these as ints
j=0 # could be done on the typeset, but needed for the sh version
echo "enter limit: \c"
read i dummy # in case we get two words; also, you should test for a bad $i
while [ $j -lt $i ]
do
eval 'var'$j'="$REAL_VALUE'$j'"'
eval 'echo "var$j is $var'$j'"'
((j = $j + 1))
done
exit
The sh version is the same except for two parts: delete the typeset,
because it's not in sh, and replace ((j = $j + 1)) with a call
j=`expr $j + 1` (which is the extra fork/exec).
>Not very elegant since a limit of 10 iterations is hard-wired. Can anybody
>think of a more concise way to do this? Using PERL is not an option, this
>must be portable sh code.
>
>The next problem is the thorny one. Some shell variables having been
>previously set up, say:
>
>var0=REAL_VALUE0
>var1=REAL_VALUE1
>var2=REAL_VALUE2
>var3=REAL_VALUE3
>var4=REAL_VALUE4
>
>I want to manipulate variable names inside the above loop such that
>I could display the "REAL VALUEx" based on the current value of $i.
Assuming that all possible REAL_VALUE* variables were defined somehow,
the two eval instructions inthe sample loop will store their contents
in the variables var0 through var${i-1} and print them out. If you're
a Rexx programmer, eval in the shell is like Rexx's interpret. The args
to eval are evaluated once (losing one level of quotation), the 'eval '
is stripped, and the resulting string is evaluated and executed.
...Kris
--
Kristopher Stephens, | (408-746-6047) | krs at uts.amdahl.com | KC6DFS
Amdahl Corporation | | |
[The opinions expressed above are mine, solely, and do not ]
[necessarily reflect the opinions or policies of Amdahl Corp. ]
More information about the Comp.unix.shell
mailing list