-1

How to have Zsh string variable containing multi words separated by space be assigned to an array so that each word is the array element

s='run help behind me'
a=($s)
m=${a[0]}
n=${a[1]}
print "m=$m"
echo n=$n

m=
n=run help behind me

confusing, so simple but still cannot do it so.. Really please help out

1 Answer 1

1

In contrast to many shells, zsh does not perform word splitting during variable expansion by default. As explained in man zshexpn, you can use the = modifier to enable splitting:

   ${=spec}
          Perform  word splitting using the rules for SH_WORD_SPLIT during
          the evaluation of spec, but regardless of whether the  parameter
          appears  in  double  quotes; if the `=' is doubled, turn it off.
          This forces parameter expansions to be split into separate words
          before  substitution, using IFS as a delimiter.  This is done by
          default in most other shells.

i.e. a=( ${=s} ) or a=( $=s ). As well, remember that zsh arrays are indexed from 1 not 0.

Those, like the a=( $s ) of bash¹ split according to complex rules involving the $IFS special characters. You can also split based on an arbitrary given string by using the s parameter expansion flag:

a=( ${(s[ ])s} ) # split $s on spaces only, discarding empty elements
a=( "${(@s[ ])s}" ) # split $s on spaces, preserving empty elements

See also Expanding variables in zsh.


¹ though note that contrary to bash, it doesn't do globbing on top of that for which you'd also need the ~ operator: a=( $=~s ).

0

You must log in to answer this question.