Shell script to create runtime variables based on the number of parameters passed in the script

Hi All,

I have a script which intends to create as many variables at runtime, as the number of parameters passed to it. The script needs to save these parameter values in the variables created and print them

abc.sh
----------
export Numbr_Parms=$#
export a=1
while [ $a -le $Numbr_Parms ]
do
export DBName_$a="$"$a
echo DBName_$a
echo $DBName_$a
a=`expr $a + 1`
done

The output this code gives is as follows :

abc.sh x y z
 
DBName_1
1
DBName_2
2
DBName_3
3

while the expected output is :

DBName_1
x
DBName_2
y
DBName_3
z
 

Thanks in advance.

Regards,
Dev

export Numbr_Parms=$#
export a=1
while [ $a -le $Numbr_Parms ]
do
eval export DBName_$a=\$$a
echo DBName_$a
eval echo \$$DBName_$a
a=`expr $a + 1`
done
1 Like

As you can see, you have to go the extra mile to achieve what you intended, and the eval has some caveats tagged to it. In recents shells, this could be done way easier using arrays:

DBname=($@)
for i in ${!DBname[@]}
  do    echo $i, ${DBname[$i]}
  done
0, x
1, y
2, z
2 Likes

Thanks Rudic, worked for me.