9

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 

3 Answers 3

13

just:

source config.file

then you could use those variables in your shell.

Sign up to request clarification or add additional context in comments.

1 Comment

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'.
9

For example here is the content of your config file:

[email protected]
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.

Comments

3

Just source the code in the beginning of your code:

. file

or

source file

4 Comments

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.
Yes, you can do it maybe in a while loop. I suggest you to Ask a question to see many different ways of doing it.
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.
@CurtSampson good one! See in here all possible combinations on this :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.