8

I have the following statement:

TOKENARRAY=($TOKEN)

$TOKEN is a numeric variable.

If I try this:

echo ${TOKENARRAY[0]}

it shows me an empty string.

If I do:

echo ${TOKENARRAY:0}

it shows me the token

But the really strange thing is that if I do:

echo ${TOKENARRAY[1]}

it shows me the token.

What's going on here? This script is supposed to work in bash, but it's not working in zsh.

2 Answers 2

5

For a script that works in both bash and zsh, you need to use a more complicated syntax.

Eg, to reference the first element in an array:

${array[@]:0:1}

Here, array[@] is all the elements, 0 is the offset (which always is 0-based), and 1 is the number of elements desired.

1
  • 1
    That will work for tokens indeed; for those needing words (as split by the shell, i.e. space, newline...) you can use the construct: $array[(w)1] to reference the first element (zsh starts at index 1 by default) and ${(w)#words} to get the number of words. NB zsh only!! Commented Mar 26, 2020 at 16:10
4

This behaviour might surprise you, depending on your programming background, but it is the desired one.

From man zshparam regarding the form ${TOKENARRAY[exp]}:

A subscript of the form [exp] selects the single element exp, where exp is an arithmetic expression which will be subject to arithmetic expansion as if it were surrounded by $((...)). The elements are numbered beginning with 1, unless the KSH_ARRAYS option is set in which case they are numbered from zero.

The syntax ${TOKENARRAY:0} is documented in man zshexpn:

${name:offset} (...) A positive offset is always treated as the offset of a character or element in name from the first character or element of the array (this is different from native zsh subscript notation). Hence 0 refers to the first character or element regardless of the setting of the option KSH_ARRAYS.

So this in principle gives your complete array (not only the first element), starting from the first character.

So, when you state

This script is supposed to work in bash, but it's not working in zsh.

you might want to consider emulate sh in your script, which enables the KSH_ARRAY option besides other ones (emulate -l sh gives you a list) or just setopt KSH_ARRAYS.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .