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