-1

i am trying to make a multidimaensional array in bash and access the elements. but its not working.

I tried with this code but there's error

# Create an indexed array to hold the inner arrays
    array=()

# Initialize the inner arrays
  array[0]=(1 2 3)
  array[1]=(4 5 6)
  array[2]=(7 8 9)

# Access elements
  element_12="${array[1][2]}"
  echo "Element at [1][2]: $element_12"

# Loop through the elements
    for ((i = 0; i < ${#array[@]}; i++)); do
        inner_array=("${array[i][@]}")  # Copy the inner array
        for ((j = 0; j < ${#inner_array[@]}; j++)); do
            echo "Element at [$i][$j]: ${inner_array[j]}"
       done
   done
4
  • 1
    Please post the exact error message. It's hard to answer "why" in relation to "not working". Your code is "working", just not the way you expect it to. It doesn't behave the way you expect it to, because it is supposed to behave in that way. Commented Sep 27, 2023 at 10:25
  • it throws the error message that you have mentioned later. is there any way to do it in bash? Commented Sep 27, 2023 at 10:35
  • 1
    bash does not have multidimensional arrays. Why would you expect, that your code works? Commented Sep 27, 2023 at 11:16
  • Also see How to declare 2D array in bash. Commented Sep 27, 2023 at 11:17

1 Answer 1

1

why my bash multidimensional array code is not working?

Because Bash does not support multidimensional arrays. In particular, Bash does not support assigning a list to an array member, which should be included in the error message:

$ array[0]=(1 2 3)                                                                                                                             
-bash: array[0]: cannot assign list to array member                                                                                              
Sign up to request clarification or add additional context in comments.

2 Comments

any other ways to do it in bash?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.