5

I'm trying to create multidimensional within arrays that are contained in an array.

tests=("'0' '1 2'" "'4' '5 6'")

in each array within tests, I want to have sub arrays. With the first array "'0' '1,2'", make another for loop to go through the contents of the sub array.

2
  • Why are you trying to force bash to do this? bash only has one-dimensional arrays. Pick the right tool for the job. Commented Jun 29, 2017 at 16:32
  • Related on unix.SE: How can I create a multidimensional array, or something similar, with bash? - as multiple people said there, if you want this, you're better off with a programming language other than the shell, such as perl or python which can still do shell-like things like easily run other programs and capture their outputs, but also have real data structures allowing arbitrary nesting of dictionaries (hashes) and lists (arrays). Commented Apr 3, 2023 at 23:24

1 Answer 1

27

Since bash 4.3. (3 levels, the first contains only one element for the demo):

arr01=(0 '1 2')
arr02=(4 '5 6')
arr1=(arr01 arr02)
arr=(arr1)

declare -n elmv1 elmv2

for elmv1 in "${arr[@]}"; do
    for elmv2 in "${elmv1[@]}"; do
        for elm in "${elmv2[@]}"; do
            echo "<$elm>"
        done
    done
done

Before 4.3

arr01=(0 '1 2')
arr02=(4 '5 6')
arr1=('arr01[@]' 'arr02[@]')
arr=('arr1[@]')

for elmv1 in "${arr[@]}"; do
    for elmv2 in "${!elmv1}"; do
        for elm in "${!elmv2}"; do
            echo "<$elm>"
        done
    done
done
Sign up to request clarification or add additional context in comments.

10 Comments

What's the point of the line declare -n elmv1 elmv2?
@clime, if you have bash 4.3 or later, type man bash and search for declare -n.
@linux_sa Sorry, still unclear. My bash 4.3.48 man says:...running declare -n ref=$1 inside the function creates ..., but the answer here states declare -n elmv1 elmv2 without the =. Is that the same? Quite unclear to me. And help declare isn't much help either: -n make NAME a reference to the variable named by its value. That is pretty much meaningless to me.
@Timo, This answer seems to explain this last sentence.
a=( 1 2 ); declare -n a=b; --> bash: declare: a: reference variable cannot be an array otherwise declare -n b=a; b=(3 4); declare -p a b
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.