Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!swrinde!cs.utexas.edu!uwm.edu!psuvax1!psuvm!blekul11!ffaac09 From: FFAAC09@cc1.kuleuven.ac.be (Nicole Delbecque & Paul Bijnens) Newsgroups: comp.unix.shell Subject: Re: problems with 'while read' Message-ID: <91126.225318FFAAC09@cc1.kuleuven.ac.be> Date: 6 May 91 22:51:18 GMT References: <3635@dagobert.informatik.uni-kiel.dbp.de> Organization: K.U.Leuven - Academic Computing Center Lines: 90 In article <3635@dagobert.informatik.uni-kiel.dbp.de>, wib@informatik.uni-kiel.dbp.de (Willi Burmeister) says: > >Just a simple (??) question: Why does this small program not work? > >------ cut here ------ cut here ------ cut here ------ cut here ------ >#!/bin/sh > >cat << EOF > hugo >one >two >three >four >EOF > >while read num >do > echo "do something with <$num>" > last=$num >done < hugo > >echo "last num = <$last>" >------ cut here ------ cut here ------ cut here ------ cut here ------ > >the output will always be: > >do something with >do something with >do something with >do something with >last num = <> > > >What I want is: > >do something with >do something with >do something with >do something with >last num = > ^^^^ You are using the Bourne shell. This shell implements the redirection of the while-loop with a subshell. And as you probably already know: you cannot get the variable from the subshell to the parent shell. (Read also the FAQ about this problem.) I have been told the Korn shell does this right... One way round this, using an ugly temporary file: trap "rm -f /tmp/sh$$; exit" 0 1 2 3 15 while read num do echo "Do something with $num" echo $num > /tmp/sh$$ done << EOF one two three EOF read last < /tmp/sh$$ echo last is $last A better way is to do some manipulation with the filedescriptors. We can avoid the redirection of the loop like this: cat > hugo << EOF one two three EOF exec 3<&0 0