Home > database >  How to retrieve the elements of lists named a1 a2 a3 in for loop?
How to retrieve the elements of lists named a1 a2 a3 in for loop?

Time:08-21

I try to make this (example...) :

list1 = ("one" "two" "three")
list2 = ("four" "five" "six")
list3 = ("seven" "eight" "nine")
listn (finite number)...

for i in {1..n}; do
    list= ${list[$i][@]}
    echo "The elements of list $i are : $list"
done

but

${list[$i][@]}

is wrong ("substitution" error).

Can you help me?

CodePudding user response:

Firstly, you cannot have spaces around the equal sign in variable assignments.

The "classical" sh answer would be to use eval, however bash has the the notion of 'nameref' variables for variable indirection. They are be declared with declare -n like so:

list1=("one" "two" "three")
list2=("four" "five" "six")
list3=("seven" "eight" "nine")

for i in {1..3}; do
    declare -n varptr=list$i
    list=${varptr[@]}
    echo "The elements of list $i are : $list"
done

Output:

$ bash /tmp/x.sh
The elements of list 1 are : one two three
The elements of list 2 are : four five six
The elements of list 3 are : seven eight nine

CodePudding user response:

You can use eval for double substitution in bash. In the first pass only inner variable is substituted and \$ is not used for substitution but replaced with $ and it is used for substitution in the second pass. Sample code is:

#! /bin/bash

list1=("one" "two" "three")
list2=("four" "five" "six")
list3=("seven" "eight" "nine")

for i in {1..3}; do
    list=$(eval echo \${list$i[@]})
    echo "The elements of list $i are : $list"
done
  •  Tags:  
  • bash
  • Related