Search code examples
zshvariable-assignment

Is there a way to split a string into an array with space(" ") separated values in ZSH?


I have this code:

carp="2 hello 192.180.00.00"
array=( ${carp} )
echo "\n${array[2]}"

and I am trying to split carp into an array named array. my output should be "hello", but it just prints blank. Is there a simple way to split carp into an array?


Solution

  • zsh has a parameter expansion syntax for that: ${=spec}. To modify your example, it would be:

    carp="2 hello 192.180.00.00"
    array=( ${=carp} )
    echo "\n${array[2]}"
    

    The description is:

    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.