LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash scripting: how can I reference a variable? (https://www.linuxquestions.org/questions/programming-9/bash-scripting-how-can-i-reference-a-variable-489904/)

frankie_DJ 10-06-2006 01:50 AM

Bash scripting: how can I reference a variable?
 
Hi everyone,

I have some variables whose names I generated when going through the loop.

for i in `seq 1 10`
do
${i}_title=some_string
done

Now I want to make references to the ${i}_title variables in another loop. How do I do that? I guess my question is how to do nested references to a variable. Thanks.

chrism01 10-06-2006 02:19 AM

The construct
${i}_title
can only be used to create a string value, not a variable name
You need to look at arrays tldp.org/LDP/abs/html/arrays.html

frankie_DJ 10-06-2006 02:38 AM

I thought about that. However, in my second loop I am going through another array. So, if I use array here, then I would have to loop through two arrays simultaneously, using the same index. This would be trivial in any other language but is it possible in bash?

EDIT: Sorry if this is confusing. I think I figured out how to get it working with arrays. Thanks

unSpawn 10-06-2006 02:55 AM

I think I figured out how to get it working with arrays.
Well, then share it with your fellow LQ members, or do you want to keep everything for yourself?

frankie_DJ 10-06-2006 05:13 AM

OK well in my first loop I am stepping through integers
1 through 11

Code:

for i in `seq 1 11`
do

Then, rather then generating title with

${i}_title=some_string

(which cannot later be referenced as a variable, so it's useless to me) I generate an array "title"
Code:

title[$i]=some_string
In my second loop I am stepping through members of a different array, which I also made to be integers (not necessarily consecutive).
Code:

for i in ${some_other_array[@]}
do

This is convinient b/c now I can reference "title" array inside of this for loop:
Code:

${title[$i]}


All times are GMT -5. The time now is 08:15 AM.