Paul L. Snyder on 19 May 2005 19:38:21 -0000

[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] bash, double for

Quoting "Paul L. Snyder" <>:

> > On Thu, May 19, 2005 at 01:32:10PM -0400, Jeff Abrahamson wrote:
> > > The variable array is space separated (so not a bash array).  I want
> > > bash to index through it like it does with command-line args and let
> > > me refer to each term in sequence.
>   foo="bar baz womble"
>   c=0
>   for e in $foo; do echo "$c is $e"; c=$(($c+1)); done

I've been playing around with this a bit, and here's one that's REALLY
short and sweet.  It's not a double-for, but it's nicely flexible if
what you really care about is indexing.

  $ str="bar baz womble"
  $ arr=($str)

And, lo!  You have a bash array.

  $ echo ${arr[1]}

For extra fun, try this with a different delimiter.  Just change the ':'
in the example below to a bash pattern matching the character or string
separating the elements in your string:

  $ patharray=(${PATH//:/ })
  $ echo ${patharray[1]}
  $ echo ${patharray[5]}

If really you want a double-for (to deal with all ordered matches in
two sets, say), try this:

  $ WHAT="IPA Gorgonzola bouillabaisse"
  $ KIND="beer cheese stew"
  $ what=($WHAT)
  $ kind=($KIND)
  $ for ((i=0; i<${#what}; i++)); do
  >   echo ${what[$i]} is a kind of ${kind[$i]}
  > done
  IPA is a kind of beer
  Gorgonzola is a kind of cheese
  bouillabaisse is a kind of stew

If you're using zsh, things will be a bit different.  You get all
sorts of new toys and zsh handles word splitting somewhat differently.
As a last bonus here's a quick zsh way to index a space-delimited

  zsh$ WHAT="IPA Gorgonzola bouillabaisse"
  zsh$ typeset -T WHAT thing ' '
  zsh$ echo $thing[2]
  zsh$ thing[2]=Taleggio
  zsh$ WHAT="IPA Taleggio bouillabaisse"

See, 'typeset -T' ties an array parameter to a string parameter, using
that last argument as a separator (or defaulting to ':'), so assignments
to the array actually change the string, and vice versa.  'PATH' is tied
to the array 'path' by default.

I like zsh.

Have fun,
Philadelphia Linux Users Group         --
Announcements -
General Discussion  --