From: dsr@mail.lns.cornell.edu (Daniel S. Riley)
Subject: Re: sh script
Date: 2000/01/26 [thread overview]
Message-ID: <shk8kwy4re.fsf@lns130.lns.cornell.edu> (raw)
In-Reply-To: 388F2BE4.F2B81A0F@sphys.unil.ch
Loris Renggli <loris.renggli@sphys.unil.ch> writes:
> Daniele Fua wrote:
> > Anyone can suggest why the attached small sh script for pseudo random
> > number generation [0-99] is not able to keep the variable $rand outside
> > the scope of the while loop? Any suggested fix?
> > ------------------------------------------------------------------------
> > #! /usr/bin/sh
> > #rand=`expr 1`
> > /bin/ps -e -o pid | while read mypid
The '|' forks a subshell for the while loop; variables can't get out
of the subshell back to the parent. For this simple case, something
like
#! /bin/sh
#rand=`expr 1`
for mypid in `/bin/ps -e -o pid`
do
if [ "${mypid}" != "PID" ]; then
rand=`expr \( "${rand}" + "${mypid}" \) % 100`
fi
echo "inside loop: rand=" ${rand}
done
echo "outside loop: rand=" ${rand}
works fine, but you may have to be trickier if you really want to
process some input a line at a time.
--
Dan Riley dsr@mail.lns.cornell.edu
Wilson Lab, Cornell University <URL:http://www.lns.cornell.edu/~dsr/>
"History teaches us that days like this are best spent in bed"
prev parent reply other threads:[~2000-01-26 5:00 UTC|newest]
Thread overview: 7+ messages / expand[flat|nested] mbox.gz Atom feed top
1998-11-04 5:00 sh script Daniele Fua
1998-11-04 5:00 ` Allan Hawdon
1998-11-04 5:00 ` Daniele Fua
1998-11-11 5:00 ` Finnbarr P. Murphy
1998-11-12 5:00 ` Robert Klima
2000-01-26 5:00 ` Loris Renggli
2000-01-26 5:00 ` Daniel S. Riley [this message]
read-only archive
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox