简体   繁体   中英

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!!!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM