home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / unix / shell / 5517 < prev    next >
Encoding:
Internet Message Format  |  1993-01-28  |  2.2 KB

  1. Path: sparky!uunet!spool.mu.edu!yale.edu!ira.uka.de!Germany.EU.net!sbsvax!mpi-sb.mpg.de!uwe
  2. From: uwe@mpi-sb.mpg.de (Uwe Waldmann)
  3. Newsgroups: comp.unix.shell
  4. Subject: Re: for loop termination
  5. Message-ID: <24206@sbsvax.cs.uni-sb.de>
  6. Date: 28 Jan 93 18:27:48 GMT
  7. References: <1993Jan27.190516.29466@relay.nswc.navy.mil>
  8. Sender: news@sbsvax.cs.uni-sb.de
  9. Reply-To: uwe@mpi-sb.mpg.de
  10. Organization: Max-Planck-Institut fuer Informatik
  11. Lines: 56
  12.  
  13. In article <1993Jan27.190516.29466@relay.nswc.navy.mil>,
  14. rweisbe@starfleet.nswc.navy.mil (Bob Weisbeck) writes:
  15. >    I'm not sure why this happens but here goes.  I have a script that 
  16. >    I'm executing but it does not terminate the loop properly and I'm
  17. >    not sure what is wrong with it. The script is as follows:
  18. > [ I've shortened the script a bit.  --uwe]
  19. > #!/bin/sh
  20. > FILES=`cat datafile`
  21. > set $FILES 
  22. > for file in $*
  23. > do
  24. >   WC=`wc -l $1  | tr -s " " | cut -f2   -d" "`
  25. >   shift 2
  26. > done
  27. > [ script performs ok, but at the end the user has to type ctrl-c to
  28. >   terminate it.  ]
  29.  
  30. Remember that the for-list (i.e. $*) is evaluated _only_once_, at the
  31. beginning of the loop.  If $* contains six words, then the loop is
  32. executed six times, no matter whether you shift once, twice, or not at
  33. all during the loop.  (To see that $file and $1 are not necessarily
  34. equal insert "echo $file $1" after the "do".)  Now, what happens after
  35. three loops?  The "shift 2" statement has been executed three times,
  36. thus the positional parameter list is empty, and so is $1 during the
  37. fourth loop.  Because "wc" is called with only one argument, namely
  38. "-l", it reads from stdin.  As there is no input from stdin, the
  39. program hangs.
  40.  
  41. The solution is, of course, to use a "while" loop.  Either
  42.  
  43.   while test $# -gt 0
  44.   do
  45.     WC=`wc -l $1  | tr -s " " | cut -f2   -d" "`
  46.     shift 2
  47.   done
  48.  
  49. or (this should be slightly faster if "test" isn't built in)
  50.  
  51.   while :
  52.   do
  53.     case $# in
  54.       0) break ;;
  55.       *) ;;
  56.     esac
  57.     WC=`wc -l $1  | tr -s " " | cut -f2   -d" "`
  58.     shift 2
  59.   done
  60.  
  61.  
  62. -- 
  63. Uwe Waldmann, Max-Planck-Institut fuer Informatik
  64. Im Stadtwald, D-W6600 Saarbruecken 1, Germany
  65. Phone: +49 681 302-5431, Fax: +49 681 302-5401, E-Mail: uwe@mpi-sb.mpg.de
  66.