Dynamic Variable in Linux

Hi All,

I am trying declare variables at runtime to use them for some calculation. What im doing is to try and run a bunch of sql queries in round-robbin fashion for few times. So im trying to create a different variable for each SQL file using the file name to keep track of the total time of individual queries.

for ((i=1;i<=$no_of_runs;i++))
do
	ls *.sql | while read SQL_FILE
	do
		start=`date +%s`;
		db2 -vtf $SQL_FILE > $SQL_FILE.out;
		end=`date +%s`;
		${SQL_FILE}_temptime=`expr $end - $start`;
		${SQL_FILE}_totaltime=`expr ${SQL_FILE}_totaltime + ${SQL_FILE}_temptime`;
	done	
done	

Now i believe this is not allowed. ${SQL_FILE}_temptime is not the way to generate/use the variable. I think the way around this problem is to use "eval". I haven't used "eval" before and im having trouble putting it to use.
Can i request someone to guide me through this problem. If i have to use eval then how can it be used in my case.

Appreciate your help.

Thanks
A

try like this:

eval ${SQL_FILE}_temptime=`expr $end - $start`;
eval ${SQL_FILE}_totaltime=`expr ${SQL_FILE}_totaltime + ${SQL_FILE}_temptime`;

Thanks for the reply Panyam.

I have already tried the approch mentioned by you and get the following error:

./Script.ksh[30]: eval: line 1: test.sql_temptime=1: no parent

It does calculate the time (1s) but gives this error as well.

A

Since your intention is just to have the temptime and totaltime for individual SQL_FILE, you can use arrays instead: (Assuming you are using bash)

declare -A temptime totaltime
for ((i=1;i<=$no_of_runs;i++))
do
	ls *.sql | while read SQL_FILE
	do
		start=`date +%s`;
		db2 -vtf $SQL_FILE > $SQL_FILE.out;
		end=`date +%s`;
                temptime[$SQL_FILE]=`expr $end - $start`
                totaltime[$SQL_FILE]=`expr ${totaltime[$SQL_FILE]} + ${temptime[$SQL_FILE]}`

	done	
done

2 arrays, temptime and totaltime are declared as associative arrays. So, the array indexes will be the filenames, and the corresponding values will contain the duration taken to execute.(BTW, you do not need expr to do the calculation. Bash can do arithmetic on its own)

Guru.

To date I've seen no good reasons for wanting a dynamic variable name. How would you even use them later?

Arrays is much better yes, since otherwise, someone could insert a row containing `rm -Rf ~/` into your database and your code would execute it!

Thanks Guru,

I am using ksh but yeah logic remains the same so it works.

Corona thanks for the tip. Will keep that in mind.

Cheers
A:b: