Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does read -a fail in zsh

Tags:

arrays

zsh

If I type:

echo "1 the
dquote> 2 quick
dquote> 3 brown" | while read -a D; do echo "${D[1]}--${D[0]}"; done

in bash it says:

the--1
quick--2
brown--3

but in zsh it says:

zsh: bad option: -a

Why? And what should I do instead?

like image 441
Adrian May Avatar asked Apr 06 '16 13:04

Adrian May


1 Answers

In both shells read is a builtin. It shares the same purpose, but the implementation and options differ.

In order to read in an array in zsh, read requires the option -A (instead of -a):

echo "1 the
2 quick   
3 brown" | while read -A D; do echo $D[2]--$D[1]; done 

Note: There are many more differences between zsh and bash:

  • In zsh arrays are numbered from one by default, in bash they start from zero.
  • echo $ARRAY prints outputs all elements in zsh but only the first element in bash
  • To print the third element of an array in sh you can use echo $ARRAY[3]. In bash braces are needed to delimit the subscript, also the subscript for the third element is 2: echo ${ARRAY[2]}.
  • In zsh you usually do not need to quote parameter expansions in order to handle values with white spaces correctly. For example

    FILENAME="no such file"
    cat $FILENAME
    

    will print only one error message in zsh:

    cat: 'no such file': No such file or directory
    

    but three error messages in bash:

    cat: no: No such file or directory
    cat: such: No such file or directory
    cat: file: No such file or directory
    
  • In zsh the builtin echo evaluates escape codes by default. In bash you need to pass the -e argument for that.

    echo 'foo\tbar'
    

    zsh:

    foo     bar
    

    bash:

    foo\tbar
    

Generally, it is important to keep in mind that, while zsh and bash are similar, they are far from being the same.

like image 178
Adaephon Avatar answered Oct 18 '22 09:10

Adaephon