简体   繁体   English

为什么在 Bash 中使用未设置的变量作为数组索引返回元素 0?

[英]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?为什么 bash 数组中的空键总是零键元素?

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. empty_key 导致循环的地方,而不是 not_existing_key。

To avoid this behavior it is obviously not to start an array with index 0为了避免这种行为,显然不要以索引 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?编辑:我的问题应该被理解为为什么这种行为是 bash 世界中的首选行为,而不是像不存在的键值那样的空结果?

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:在没有参数扩展语法的情况下使用时,null 或 unset 变量的名称被评估为0

     $ notset= $ echo ${arr[notset]} a
  • and finally (your question), a null value evaluates to 0 :最后(你的问题),一个空值计算为0

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

Manual quotes:手动报价:

  • Arrays :数组

    Indexed arrays are referenced using integers (including arithmetic expressions (see Shell Arithmetic )) [...]索引数组使用整数(包括算术表达式(参见Shell 算术))进行引用 [...]

  • 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.在表达式中,shell 变量也可以在不使用参数扩展语法的情况下按名称引用。 A shell variable that is null or unset evaluates to 0 when referenced by name without using the parameter expansion syntax.在不使用参数扩展语法的情况下按名称引用时,为 null 或未设置的 shell 变量的计算结果为 0。 [...] A null value evaluates to 0. [...]空值的计算结果为 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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