home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / unix / shell / 3919 < prev    next >
Encoding:
Text File  |  1992-09-11  |  1.7 KB  |  45 lines

  1. Newsgroups: comp.unix.shell
  2. Path: sparky!uunet!uunet.ca!wildcan!sq!msb
  3. From: msb@sq.sq.com (Mark Brader)
  4. Subject: Re: How to do $#a in Bourne shell?
  5. Message-ID: <1992Sep12.022450.20682@sq.sq.com>
  6. Organization: SoftQuad Inc., Toronto, Canada
  7. References: <peter.716085132@merlin> <1992Sep10.190928.7699@oracle.us.oracle.com>
  8. Date: Sat, 12 Sep 92 02:24:50 GMT
  9. Lines: 34
  10.  
  11. > > If I have a list in Bourne shell, how can I determine how many
  12. > > elements are in, short of write a for loop and counting them?
  13.  
  14. I assume that "a list" means "a variable containing a number of items
  15. delimited by spaces", so that "  a  b  "  and "a b" each have 2 elements.
  16. Assuming that $list is the variable, then the simplest way is:
  17.  
  18.     listcount=`set dummy $list; shift; echo $#`
  19.  
  20. If you know that there's at least one element, you can omit the "dummy"
  21. and the "shift;".  Otherwise those are necessary because of the way that
  22. sh overloads the "set" command.  Of course, you don't need to assign
  23. the result to a variable (listcount) unless you want to.
  24.  
  25. Someone else posts a long solution, which would also work if it did not
  26. include the lines:
  27.  
  28. > echo "FIRST SAVE THE COMMAND LINE ARGUMENTS"
  29. > args=$@
  30. > ......
  31. > echo "FINALLY, RESTORE THE COMMAND LINE ARGUMENTS"
  32. > set $args
  33.  
  34. This fails badly if there was any whitespace in the command line arguments.
  35. [And I do mean *was*. :-)]  The general approach can be made to work,
  36. I guess, but it's a lot easier to just go into a subshell and change
  37. the arguments in there.  And the `...` gives you the subshell.
  38.  
  39. -- 
  40. Mark Brader            "The spaghetti is put there by the designer of
  41. SoftQuad Inc., Toronto         the code, not the designer of the language."
  42. utzoo!sq!msb, msb@sq.com                -- Richard Minner
  43.  
  44. This article is in the public domain.
  45.