Zsh - split string by spaces when using dot operator Zsh - split string by spaces when using dot operator shell shell

Zsh - split string by spaces when using dot operator


Lists should never be represented as strings. Use array syntax.

list=( a b c )for i in "${list[@]}"; do  echo "$i"done

There are several reasons this is preferable.

In ZSH:

  • ZSH breaks POSIX by not performing string-splitting at all on unquoted expansions unless they explicitly request it. You can make this request by either running setopt sh_word_split, or using the parameter expansions ${=list} or ${(ps: :)list}

In other Bourne-derived shells:

  • String-splitting is dependent on the value of IFS, which cannot be guaranteed to be at defaults, especially when sourced from a separate script (which may have changed it locally).
  • Unquoted expansion also performs globbing, which can have different results depending on which files are in the current working directory (for instance, if your list contains hello[world], this will behave in an unexpected manner if your current directory contains files named hellow, helloo, or otherwise matching the glob).
  • Avoiding the globbing step is not only more correct, but also more efficient.


Whilst I note the comment regarding lists by Charles Duffy, this was my solution/test.

#!/bin/zshfunction three(){        first=$1        second=$2        third=$3        echo "1: $first 2: $second 3:$third"}setopt sh_word_splitset "1 A 2" "2 B 3" "3 C 4" "4 D 5"for i;do        three $i; done

This will output

1: 1 2: A 3:21: 2 2: B 3:31: 3 2: C 3:41: 4 2: D 3:5