Assigning variable values on the fly in bash

2019-03-02 17:58发布

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.

标签: bash shell
1条回答
Viruses.
2楼-- · 2019-03-02 18:32

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

#!/bin/bash

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>
查看更多
登录 后发表回答