2

I have two arrays which I would like to dynamically assign to a variable depending on user input

ARRAY_ONE=('one' 'two')
ARRAY_TWO=('three' 'four')

Suppose that $opt can be either ONE or TWO depending on user input. I have a variable ARRAY_THREE that I would like to assign to the content of either ARRAY_ONE or ARRAY_TWO depending on the value of $opt.

The following snippet does not work, as it only takes the element in the first position of the assigned array:

TEMP=ARRAY_$opt
ARRAY_THREE=${!TEMP}
echo $ARRAY_THREE     # 'one'

3 Answers 3

4

Change your code to:

TEMP=ARRAY_$opt[@]
ARRAY_THREE=(${!TEMP})
echo ${ARRAY_THREE[@]}

OUTPUT:

three four

EDIT:

Live Demo: http://ideone.com/hocG24

Sign up to request clarification or add additional context in comments.

2 Comments

@perreal: Pls check the linked demo.
@perreal: Edited the demo to add echo ${ARRAY_THREE[0]} and echo ${ARRAY_THREE[1]}
3
$ opt=ONE
$ TEMP="ARRAY_${opt}[@]"
$ ARRAY_THREE=( "${!TEMP}" )
$ set|grep ^ARRAY_
ARRAY_ONE=([0]="one" [1]="two")
ARRAY_THREE=([0]="one" [1]="two")
ARRAY_TWO=([0]="three" [1]="four")

Comments

0

Here is my solution that does not use a temp variable:

#!/bin/bash

foo_1=(fff ddd) ;
foo_2=(ggg ccc) ;

for i in 1 2 ;
do
    eval mine=( \${foo_$i[@]} ) ;
    echo ${mine[@]} ;
done ;

Comments

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.