Subhayan Bhattacharya Subhayan Bhattacharya -4 years ago 111
Bash Question

Assigning variable values on the fly in bash

I have the below config file : OO_CONF.conf with the below contents:

appPackage_name = sqlncli
appPackage_version = 11.3.6538.0

Now i want to read these variables inside my shell script. So i want a variable $appPackage_name and it should contain the value: sqlncli

The way i am trying to do this is :

while read line; do
newline=`echo $line | sed -e 's/ //g'`
expr "$newline"
done < ./OO_CONF.conf

echo "$appPackage_name"

But it does not seem to work.

Request some help on this please.

Answer Source

Use the declare built-in in bash with -g flag to make it globally available,


while IFS=' = ' read -r  key value; do
    declare -g $key="$value"
done <OO_CONF.conf

printf "%s %s\n" "${appPackage_name}" "${appPackage_version}"

The idea is to set the IFS to = so to split the lines in the file to read the key and value pairs and then with declare we can create variables on the fly with the below syntax

declare -g <var-name>=<variable-value>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download