8

I have a text configuration file something like this :

## COMMENT
KEY1=VALUE1  ## COMMENT
KEY2=VALUE2

KEY3=VALUE3  ## COMMENT

## COMMENT

As you can see, this has key value pairs, however it also contains comment lines and blank lines. In some cases, the comments are on the same line as the key value pair.

How do I read this config file and set the keys as variable names in a shell script so that I can use them as :

echo $KEY1 
user1691717
  • 213
  • 1
  • 7
  • 15

3 Answers3

12

just:

source config.file

then you could use those variables in your shell.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • Just for curious, Is it possible to find a key name dynamically from a configuration file. In other words, 'Need not to check a keywords at the script to retrieve values or perform action. Just have to retrieve a values of a key one by one in the script'. – ArunRaj Apr 04 '14 at 05:32
8

For example here is the content of your config file:

email=test@test.com
user=test
password=test

There are two ways:

  1. use source to do it.

    source $<your_file_path>
    echo $email
    
  2. read content and then loop each line to compare to determine the correct line

    cat $<your_file_path> | while read line
    do 
      if [[$line == *"email"*]]; then
        IFS='-' read -a myarray <<< "$line"
        email=${myarray[1]}
        echo $email
      fi
    done
    

The second solution's disadvantage is that you need to use if to check each line.

Haimei
  • 12,577
  • 3
  • 50
  • 36
3

Just source the code in the beginning of your code:

. file

or

source file
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Just for curious, Is it possible to find a key name dynamically from a configuration file. In other words, **Need not to check a keywords at the script to retrieve values or perform action. Just have to retrieve a values of a key one by one in the script**. – ArunRaj Apr 04 '14 at 05:40
  • 1
    Yes, you can do it maybe in a `while` loop. I suggest you to [Ask a question](http://stackoverflow.com/questions/ask) to see many different ways of doing it. – fedorqui Apr 04 '14 at 08:20
  • 1
    Be careful when doing this that your configuration file actually uses shell syntax to handle things like spaces. For example, the line `s1="foo bar"` will work, but the line `s2=foo bar` will fail as the shell will interpret that as a request to run the program `bar` with `s2=foo` set in the environment. – cjs Aug 18 '16 at 04:50
  • @CurtSampson good one! See in [here](http://stackoverflow.com/a/2268117/1983854) all possible combinations on this :) – fedorqui Aug 18 '16 at 07:12