home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!spool.mu.edu!yale.edu!ira.uka.de!Germany.EU.net!sbsvax!mpi-sb.mpg.de!uwe
- From: uwe@mpi-sb.mpg.de (Uwe Waldmann)
- Newsgroups: comp.unix.shell
- Subject: Re: for loop termination
- Message-ID: <24206@sbsvax.cs.uni-sb.de>
- Date: 28 Jan 93 18:27:48 GMT
- References: <1993Jan27.190516.29466@relay.nswc.navy.mil>
- Sender: news@sbsvax.cs.uni-sb.de
- Reply-To: uwe@mpi-sb.mpg.de
- Organization: Max-Planck-Institut fuer Informatik
- Lines: 56
-
- In article <1993Jan27.190516.29466@relay.nswc.navy.mil>,
- rweisbe@starfleet.nswc.navy.mil (Bob Weisbeck) writes:
- > I'm not sure why this happens but here goes. I have a script that
- > I'm executing but it does not terminate the loop properly and I'm
- > not sure what is wrong with it. The script is as follows:
- >
- > [ I've shortened the script a bit. --uwe]
- >
- > #!/bin/sh
- > FILES=`cat datafile`
- > set $FILES
- > for file in $*
- > do
- > WC=`wc -l $1 | tr -s " " | cut -f2 -d" "`
- > shift 2
- > done
- >
- > [ script performs ok, but at the end the user has to type ctrl-c to
- > terminate it. ]
-
- Remember that the for-list (i.e. $*) is evaluated _only_once_, at the
- beginning of the loop. If $* contains six words, then the loop is
- executed six times, no matter whether you shift once, twice, or not at
- all during the loop. (To see that $file and $1 are not necessarily
- equal insert "echo $file $1" after the "do".) Now, what happens after
- three loops? The "shift 2" statement has been executed three times,
- thus the positional parameter list is empty, and so is $1 during the
- fourth loop. Because "wc" is called with only one argument, namely
- "-l", it reads from stdin. As there is no input from stdin, the
- program hangs.
-
- The solution is, of course, to use a "while" loop. Either
-
- while test $# -gt 0
- do
- WC=`wc -l $1 | tr -s " " | cut -f2 -d" "`
- shift 2
- done
-
- or (this should be slightly faster if "test" isn't built in)
-
- while :
- do
- case $# in
- 0) break ;;
- *) ;;
- esac
- WC=`wc -l $1 | tr -s " " | cut -f2 -d" "`
- shift 2
- done
-
-
- --
- Uwe Waldmann, Max-Planck-Institut fuer Informatik
- Im Stadtwald, D-W6600 Saarbruecken 1, Germany
- Phone: +49 681 302-5431, Fax: +49 681 302-5401, E-Mail: uwe@mpi-sb.mpg.de
-