1

I have this little piece of code:

#!/bin/bash

item01=('item1' '1' '20')
item02=('item2' '4' '77')
item03=('item3' '17' '15')
zeroone=01
zerotwo=02


echo ""
declare -a array=()
array=${item$zeroone[@]}
echo ""
echo ${array[@]}
echo ""

Obviously this doesn't work (bad substitution).

Is there a way to make it work? Such that a variable can be a part of an array name?

And also, to make this work in particular:

array[0]=${item$zeroone[0]}

and

another_variable=${item$zeroone[0]}

Thx

1 Answer 1

2

Better use associative arrays:

declare -A item=([1, 0]='item1' [1, 1]='1' [1, 2]='20')
...

Accessing an element:

one=1
echo "${item[$one, 0]}"

On a loop:

for ((I = 0; I <= 2; ++I)); do
    echo "${item[$one, $i]}"
done

You can also use strings instead of numbers:

declare -A item=(["01", 0]='item1' ["01", 1]='1' ["01", 2]='20')

Another answer: You can actually use references:

item01=('item1' '1' '20')
item02=('item2' '4' '77')
item03=('item3' '17' '15')
zeroone=01
zerotwo=02

echo ""
ref="item${zeroone}[@]"
declare -a array=("${!ref}")  ## Still produces 3 arguments as if "${item01[@]}" was called
echo ""
echo "${array[@]}"
echo ""
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.