简体   繁体   中英

Why does using an unset variable as the array index return element 0 in Bash?

Why is an empty key in a bash array always the zero key element?

Try

empty_key=

h[0]=0
h[1]=1
h[2]=2

echo ${h[$empty_key]}

Result

0

Could you please explain, why this behavior is correct?

In my understanding it should not be different to

not_existing_key=5 
echo ${h[$not_existing_key]}

where the result is just empty.

This is important to understand, if one uses the result for a loop, like in

for element in ${h[$key]};do
  ...
done

where the empty_key leads to a cycle, but NOT the not_existing_key.

To avoid this behavior it is obviously not to start an array with index 0

OR

replace an empty key by any key value not assigned (what seems to be boring).

Again my question: why is this behavior correct?

EDIT: My question should be understood as why is this behavior the prefered one in the bash world and not an empty result as with a non-existing key value?

When accessing an array element, [] constitutes an arithmetic context. This has a few consequences:

  • no need for $ to dereference variables:

     $ arr=(abc) $ idx=1 $ echo ${arr[idx]} b
  • arithmetic operations are evaluated:

     $ echo ${arr[idx+idx]} c
  • variable names are dereferenced in "chains" ( evaluated as an arithmetic expression in the manual):

     $ idx=2 $ idxref=idx $ echo ${arr[idxref]} c
  • names of null or unset variables are evaluated to 0 when used without parameter expansion syntax:

     $ notset= $ echo ${arr[notset]} a
  • and finally (your question), a null value evaluates to 0 :

     $ notset= $ echo {$arr[$notset]} a

Manual quotes:

  • Arrays :

    Indexed arrays are referenced using integers (including arithmetic expressions (see Shell Arithmetic )) [...]

  • Shell Arithmetic :

    Shell variables are allowed as operands; parameter expansion is performed before the expression is evaluated. Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax. A shell variable that is null or unset evaluates to 0 when referenced by name without using the parameter expansion syntax. [...] A null value evaluates to 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM