1

Both bash and zsh support reading a file into an array, I'm used to the bash's way and am appalled by the zsh's behaviour: zsh starts the array from index 1! That's not the unix way.

Here is an example, let's create a file:

echo yay1 >> pp
echo yay2 >> pp
echo yay3 >> pp

And use the bash mapfile (-t prevents the newlines to be sucked into the array elements):

[~]$ mapfile -t arr < pp
[~]$ echo "${arr[0]}"
yay1
[~]$ echo "${arr[1]}"
yay2
[~]$ echo "${arr[2]}"
yay3

Cool, that's what I'm used to. Now let's try zsh (we need to load the module):

% zmodload zsh/mapfile                     
% arr=("${(f@)mapfile[pp]}")
% echo "${arr[0]}"          

% echo "${arr[1]}"
yay1
% echo "${arr[2]}"
yay2
% echo "${arr[3]}"
yay3

Ooops, that's not the unix way of indexing things.

How can I make the zsh's mapfile to start the array from index 0?

grochmal
  • 8,657
  • @jasonwryan - Nice, so it is bash (or better, Korn's) behaviour that's inconsistent. 'tis a dupe alright. The actual "solution" is to start using i-1 in bash. Thanks – grochmal Nov 26 '16 at 21:02
  • 1
    There is the option of setopt -o KSH_ZERO_SUBSCRIPT or the more coarse setopt -o KSH_ARRAYS. Both will allow the use of zero array, but the seconds has some other (additional) consequences. –  Nov 29 '16 at 07:19
  • @sorontar - God bless I have not tried yet rewriting the script that i'm moving to zsh (don't ask why, it is just a horrible violation of "if it ain't broke don't fix"). That's a lot easier. Thanks – grochmal Nov 30 '16 at 03:35

0 Answers0