From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f678f,956a24d31e0300cf X-Google-Attributes: gidf678f,public From: dsr@mail.lns.cornell.edu (Daniel S. Riley) Subject: Re: sh script Date: 2000/01/26 Message-ID: #1/1 X-Deja-AN: 577987042 References: <36406956.3F54@g24ux.phys.uniroma1.it> <388F2BE4.F2B81A0F@sphys.unil.ch> Organization: LNS, Cornell U., Ithaca, NY 14853 Newsgroups: comp.unix.osf.misc Loris Renggli 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 "History teaches us that days like this are best spent in bed"