/bin/sh: How to retain variables set in a while loop?

Darin McGrew mcgrew at ichthous.Eng.Sun.COM
Thu Mar 7 04:34:46 AEST 1991


root at lingua.cltr.uq.OZ.AU (Hulk Hogan) writes:
>Hi. I guess this is probably a FAQ, but here goes anyway...
>Platform: Sun4.   OS: SunOS 4.x.
>I have written some Bourne shell script which sets some variables within 
>the body of a while loop. After the loop finishes, the variables are no
>longer set.  How can I retain these values after the while loop?
>I've tried an export within the body of the while, but that didn't work.
>
>I remember reading somewhere that the body of a while loop is executed in
>sub-shell, and that's why the behavious occurs. I really don't care how
>the shell does while loops. I just want my variables!

If the while loop has its stdio redirected in any way, it is put
in a subshell.  (Likewise with for loops, case statements, etc.)
The subshell has no way to pass variables back to its parent
shell.

>I can use a combination of head, tail and cut to get the results I
>want, but it would be so much easier if I could just use while.

Another approach would be to write the values of the variables
into temporary files, and then read them back, but that isn't
really a great solution either.

I'd try avoiding putting the while loop into a subshell by doing
the io redirection in the parent shell.  Your example becomes--

    exec < $UIDRANGES
    num=0
    while [ $num -le $choice ]
    do
         read minuid maxuid title
         echo "DEBUG: $num      $title  $minuid         $maxuid"
         num=`expr $num + 1`
    done < $UIDRANGES
 
    echo "After while: num=$num title=$title minuid=$minuid maxuid=$maxuid"

If you need your original io at some point after the while loop,
there are games you can play with `exec 3<&0` and `exec 0<&3` to
save stdin as file descriptor 3 (typically unused) beforehand,
and then restore stdin from file descriptor 3 when you're done.

                 Darin McGrew
           mcgrew at Eng.Sun.COM   "Christianity isn't a crutch; it's a stretcher.
       Affiliation stated for    You can't even hobble into heaven."
identification purposes only.



More information about the Comp.unix.shell mailing list