ipin
ipin

Reputation: 9

How to import a config file variable, but use a different separator?

First, source and . are not working as I'm using a different kind of separator, which is something like.

I have tried several methods I can google, but didn't have any luck so far.
I managed to print out all the variables and values correctly, but I can't store it as a variable in this bash process.

What I want:

At end of the bash process when I "echo $HUA_IP:"
it should give me "192.168.0.1" as per the config.cf file.

File config.cf:

  "HUA_PASSWORD": "admin",
  "HUA_IP": "192.168.0.1"

While my bash file is:

#!/bin/bash

configFile="/opt/config.cf"
# config="`cat $configFile`"
# echo $config
# source $configFile
# echo $var1
# conf="";

while read var value
do
    # export "$var"="$value"
    var="${var%:*}"
    var="${var//\"/}"
    var="${var//[\}\{]/}"
    value="${value//\"/}"
    value="${value//,/}"
    # echo "var :'"$var"'"
    # echo "value :'"$value"'"

    if [ !$var = "" ]
    then
        # "$var"="$value"
        # eval $var=$value
        export "$var"="$value"
    fi

done < $configFile

echo $HUA_IP:

Upvotes: 0

Views: 100

Answers (2)

John1024
John1024

Reputation: 113924

Try:

while read -r line; do
    line=${line//\"/}
    declare -x "${line/: /=}"
done<config.cf
echo "$HUA_IP"

When this code is run, the output is:

192.168.0.1

How it works

The key here is that declare, which is a bash builtin, allows you to use a bash variable to create and assign another variable. As a simple example:

$ x="a=b";  declare -x "$x"; echo "$a"
b

Now, let's apply this to your input file:

  • while read -r line; do

    This starts a loop reading one line of input at a time.

  • line=${line//\"/}

    This removes all double-quotes from the input line.

  • declare -x "${line/: /=}"

    This replaces : with = in line and then creates a variable using declare.

    The -x option tells bash to export the variable that is declared.

  • done <config.cf

    This tells the loop to get its stdin from config.cf.

Upvotes: 1

mik1904
mik1904

Reputation: 1365

Your code, even if it could be not the best approach, is working if you change your if condition. The correct way is:

#...
if [ ! -z $var  ]
then
    # "$var"="$value"
    # eval $var=$value
    export "$var"="$value"
fi

Upvotes: 0

Related Questions