user1989706
user1989706

Reputation: 25

Dynamic Shell Variable substitution

I have a question about Shell Variable substitution.

Requirement: I need to insert something to mysql db.And I don't want to write the insert script in main shell ,so I would like to define a insert sql script as a variable $SQL . This variable and many other variables are stored in another file named sql.cfg

but this variable will refer another variable $Value. when i execute the main shell, the $Value will be replace by actually value。

Example: in sql.cfg

SQL="insert into table column1,column2 values($Value1,$Value2)"
DB_NAME=dbname
DB_IP=192.168.0.x
USR=username
PWD=password

in main.sh

. ./sql.cfg

Value1=100
Value2=200

` mysql $DB_NAME -h$DB_IP -u $USR -p$PWD -se "$SQL;"`

Question:

How can I substitute the $sql with $Value1 $Value2 properly so that I can insert them into to mysql db?

Thanks a lot!!!

Upvotes: 1

Views: 647

Answers (1)

Kent
Kent

Reputation: 195079

you have to set Value1,Value2 in your main.sh before you load/source your sql.cfg

example:

kent$  head *           
==> main.sh <==
#!/bin/bash
Value1=100
Value2=200
source sql.cfg
echo "$DB_NAME - $SQL"



==> sql.cfg <==
#!/bin/bash
SQL="insert into table column1,column2 values($Value1,$Value2)"
DB_NAME=dbname
DB_IP=192.168.0.x
USR=username
PWD=password

kent$  ./main.sh
dbname - insert into table column1,column2 values(100,200)

And if you really want to load the sql.cfg first and set the value in your main.sh later. you could change the $Value1,2 in your sql.cfg as placeholders, and in main.sh substitute those values as you want. See the example:

kent$  head *
==> main.sh <==
#!/bin/bash
source sql.cfg

Value1=444
Value2=555

SQL=$(sed "s/:Value1/$Value1/g; s/:Value2/$Value2/g" <<<$SQL)

echo "$DB_NAME - $SQL"


==> sql.cfg <==
#!/bin/bash
SQL="insert into table column1,column2 values(:Value1,:Value2)"
DB_NAME=dbname

kent$  ./main.sh
dbname - insert into table column1,column2 values(444,555)

Upvotes: 1

Related Questions