Trouble with variable assignment and reading in shell scripting

Hi,
I have an inputfile with some table names in it.
For ex:

t_arnge
t_profl
t_fac

I need a script which reads the line one by one and need to assign to some dynamic variable. If to explain the above example:

i need some

a=table_name1
table_name1=t_arnge

in first time and

a=table_name2
table_name2=t_profl

while running second time and

a=table_name3
table_name3=t_fac

.

can any one please help me in this matter. It's a kind of urgent. I am using shell scripting.

Using array is the best option for this requirement.

You could code something like below:

#!/bin/bash

typeset -a table_name
typeset -i c

while read tn
do
        (( ++c ))
        table_name[c]="${tn}"
done < inputfile

Now you have each table names stored in the indexed array.

For further reference refer: Bash Array (link removed)

1 Like

Few questions:
I need table_name[c] value in another variable. for ex:a
SO, if i echo $a , it should give table_name1
if i echo $table_name1 it should give the first table name in the i/p file.

Can't we do it in simple scripting? i mean using loops?

Once you have the values stored in indexed array, then why you want them in a different variable?

By the way you can visit each array element using a for loop and assign it to another variable if required:

for tn in ${table_name[@]}
do
        echo "$tn"
        # you can assign a="$tn" here
done

We get asked for dynamic variable names many times a week, but these requests remain ill-considered... How could you even tell how many you had when you were done? How would you use it? And other such questions. It's extremely awkward, error-prone, and insecure in more ways than I can describe in a short post.

In short -- variables don't work that way. Not in shell, not in any other language that springs to mind. Either arrays or simple strings more than suffice for the purpose, that being what they were meant to do.