Bash – Split string by space in ZSH

arraybashreadzsh

Give this file.txt:

first line
second line
third line

This works in bash:

while IFS=' ' read -a args; do
  echo "${args[0]}"
done < file.txt

To produce

first
second
third

That is to say, we were able to read the file line by line, and on each one we split the line further into an array using space as a delimiter. But in zsh, the result is an error: read: bad option: -a.

How can we achieve in zsh the same as in bash? I’ve tried several solutions, but I was never able to split a string into an array using spaces as the delimiter.

Best Answer

From man zshbuiltins, zsh's read uses -A instead.

read [ -rszpqAclneE ] [ -t [ num ] ] [ -k [ num ] ] [ -d delim ]
     [ -u n ] [ name[?prompt] ] [ name ...  ]
...
       -A     The  first  name  is taken as the name of an array
              and all words are assigned to it.

Hence the command is

while IFS=' ' read -A args; do
  echo "${args[1]}"
done < file.txt

N.B. by default, zsh array numbering begins with 1, whereas bash's begins with 0.

$ man zshparam
...
Array Subscripts
...
The elements are numbered  beginning  with  1, unless the
KSH_ARRAYS option is set in which case they are numbered from zero.