LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   reference bash array values, using a variable with a value of the array name (https://www.linuxquestions.org/questions/programming-9/reference-bash-array-values-using-a-variable-with-a-value-of-the-array-name-933067/)

gusthecat 03-06-2012 02:19 PM

reference bash array values, using a variable with a value of the array name
 
In my script I have several arrays and as part of the processing I figure out the names. Once
I have the name I assign it to a variable. Now the hard part. How do I process/reference the array based on the variable name. I have tried several things and best I can come up with is the first index only

ex.
array1=("hello gus" "goodbye world" "I need help")
refarray1=array1

How do I use refarray1 or manipulate refarray1 in order to get the values of the array.

thanks

catkin 03-06-2012 08:33 PM

Are you using a version of bash that supports associative arrays? They were introduced in version 4.0.

grail 03-07-2012 01:38 AM

Probably need to explain some more gus as I am a bit lost?

gusthecat 03-07-2012 08:45 AM

thanks for the replies but I came up with a different solution.

grail 03-07-2012 09:46 AM

And would you like to share with the class so everyone may benefit?

gusthecat 03-07-2012 03:41 PM

sorry I should have provided a bit more detail before marking solved.

Initially I didn't actually solve my original issue I just reworked the script to avoid the situation.

However, I didn't give up and did in fact find the solution. Now I'll rework the script again because its a better implementation.


array1=("hello gus" "goodbye world" "I need help")
refarray1=array1

I started with above and wanted to know how to use refarray1 to refer to the elements in the array1.
The solution was to correctly deference refarray1. I was not getting that part correct.

These 2 for loops produce same output

# using array1
for((x=0; x < ${#array1[@]}; x += 1))
do
echo ${array1[$x]}

done

#using refarray
eval no_elem=\${#${refarray1}[@]}
for((x=0; x < $no_elem; x += 1))
do
eval echo \${${refarray1}[$x]}

done

the 2 for loops are equivalent. the second version is where I was stuck


All times are GMT -5. The time now is 01:11 AM.