Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read values from configuration file and use in shell script

Tags:

shell

config

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 
like image 360
user1691717 Avatar asked Sep 13 '13 15:09

user1691717


People also ask

How Use config file in Unix shell script?

Use of external configuration files prevents a user from making changes to a script. Config file is added with the help of source command. If a script is shared in many users and every user need a different configuration file, then instead of changing the script each time simply include the config files.

How read config file in Linux?

conf file in Linux, first locate it in the file system. Most often, the dhclient. conf file will be located in the /etc or /etc/DHCP directory. Once you find the file, open it with your favorite command-line editor.


3 Answers

just:

source config.file

then you could use those variables in your shell.

like image 199
Kent Avatar answered Jan 04 '23 06:01

Kent


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.

like image 43
Haimei Avatar answered Jan 04 '23 05:01

Haimei


Just source the code in the beginning of your code:

. file

or

source file
like image 23
fedorqui 'SO stop harming' Avatar answered Jan 04 '23 05:01

fedorqui 'SO stop harming'