michael nesterenko
michael nesterenko

Reputation: 14439

Unbound variable during associative array initialization and access

With enabled unbound variables check (set -u), bash fails to initialize and access associative array:

during initialization

set -u
declare -a qwe=()
qwe[asd]=val # bash: asd: unbound variable

during access:

declare -a qwe=()
qwe[asd]=val
set -u
echo ${qwe[asd]} # bash: asd: unbound variable

Bash version: GNU bash, version 5.1.4(1)-release (x86_64-pc-linux-gnu)

Am I missing something or it is some kind of a bug?

Upvotes: 1

Views: 787

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52152

qwe is an array, with integer indexing. When you write qwe[asd], Bash knows that asd has to be an integer, so it tries to get the value of a variable $asd (it handles the content of the square brackets as an "arithmetic context"); if it is unset, it would default to 0, but because of set -u, you get an error instead.

Did you mean declare -A for an associative array?

Upvotes: 5

Related Questions