-2

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
bloumk
  • 1
  • 1
  • Welcome to Stack Overflow! Please take the [tour]. For help with a code problem here, we require a [mre], which means the code needs to replicate the problem you're describing. This code does not; it has a syntax error on line 1. Please [edit] to fix it. For more tips, see [How to ask a good question](/help/how-to-ask). – wjandrea Aug 20 '22 at 19:58
  • Also, `{1..n}` doesn't do brace expansion, and `list= ${...}` should be `list=${...}`. – wjandrea Aug 20 '22 at 20:00

2 Answers2

1

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
TheMadsen
  • 196
  • 1
  • 11
0

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
  • Thank you Özgür Murat Sağdıçoğlu for your help !! – bloumk Aug 20 '22 at 19:49
  • [Why should eval be avoided in Bash, and what should I use instead?](https://stackoverflow.com/questions/17529220/why-should-eval-be-avoided-in-bash-and-what-should-i-use-instead#:~:text=There%20are%20many%20shell%20constructs,how%20it%20could%20be%20exploited.) – tshiono Aug 21 '22 at 22:03