0

I am confused about how to declare an array in bash.

Presume:

$arr[1]=x
$arr[2]=y
$arr[3]=z

Code:

declare -A/-a object
fo var in ${arr[@]}
do
    object["a"]="${arr[1]}"
    object["b"]="${arr[2]}"
    object["c"]="${arr[3]}"
    echo ${object["a"]}
done

Output: z

What I want is :x

If I commented object["b"] and object["c"], then the output is correct:x

No matter -A or -a, still does not work. is this problem related to my bash environment?

GNU bash,version 3.2.57(1) -release (x86_64_apple-darwin18)

YYZZYY
  • 31
  • 5

1 Answers1

0

The indexed array requires the subscript must be evaluated to a number. In this case, object["a"] object["b"] object["c"] is treated as object[0] object[0] object[0] Associate array can be used if the key is an arbitrary string. To declare it using -A instead of -a

-a Each name is an indexed array variable (see Arrays above).

-A Each name is an associative array variable (see Arrays above).

nhatnq
  • 1,173
  • 7
  • 16