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


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.

  • Can you use the cut binary? It is not a shell built-in, but it will do what you want via cut -d ' ' -f 1 file.txt. Feb 14, 2019 at 5:10
  • @JeremyDover It would work for this case, but I want something more robust, hence asking for an array.
    – user137369
    Feb 14, 2019 at 5:17

1 Answer 1


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.
  • 2
    You are correct. I had tried -A but it did not seem to be working. It was a combination of the 1-based index plus the differences in slicing that were tripping me up.
    – user137369
    Feb 14, 2019 at 5:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.