I am writing a for loop that will go through this file line by line creating a variable of itself. Using the first iteration of the loop (i.e. the first line) as an example, I want it to create a variable called
db_serial and populate it with value 0623AN1208
on the next iteration create a variable called
db_hostname and populate it with value server1
etc etc
so i have tried
cat /tmp/CMDB | while read n
do
VAR=db_`echo $n | cut -d: -f1`
VALUE=`echo $n | cut -d: -f2`
eval `echo $VAR`=`echo $VALUE`
done
# echo it all out after the loop has finished
echo "DB serial is set to $db_serial"
echo "DB hostname is set to $db_hostname"
echo "DB model is set to $db_model"
echo "DB Asset ID is set to $db_assetID"
Plus a whole load of other combinations and i just cant get the thing to work
Im sure the problem is with my use of the "eval" command which is effectively using another variable to create a variable, and assigning the value from another variable
thanks Jim, the thing is, the file /tmp/CMDB will have thousands of values. i have just given four (serial, hostname, assetid and model). The object of the script is to create a variable from the name defined to the left of the colon regardless of what it is, so my script shouldn't have any references to the "actual" variable names. e.g hostname or assetID etc.
If that file happens to have a line like this
bananas: woohoo
then i want a variable created called db_bananas with a value of "woohoo" ... but it will always be the case that ill have no idea what will be in that file
The problem is not the eval expression, but the fact that pipes are executed in subshells. Therefore, variables created in while loop remain unset outside of it.
Try redirecting input without using a pipe:
while read n
do
VAR=db_`echo $n | cut -d: -f1`
VALUE=`echo $n | cut -d: -f2`
eval `echo $VAR`=`echo $VALUE`
done < /tmp/CMDB
# echo it all out after the loop has finished
echo "DB serial is set to $db_serial"
echo "DB hostname is set to $db_hostname"
echo "DB model is set to $db_model"
echo "DB Asset ID is set to $db_assetID"
Also, the $VALUE variable has a leading space in it. You should strip it off, by using
Thank you danmero and others, With respect to your comment above, you will see from the OP that i have indeed given clear examples of what I had tried and I have expressed that after multiple attempts at different solutions i found myself banging my head against a wall with this one.... So to say " try to solve your own problems !" I think is a little harsh