Alichino
Alichino

Reputation: 1736

A variable as part of array name

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

Upvotes: 1

Views: 235

Answers (1)

konsolebox
konsolebox

Reputation: 75488

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 ""

Upvotes: 2

Related Questions