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
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.
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.
just:
source config.file
then you could use those variables in your shell.
For example here is the content of your config file:
[email protected]
user=test
password=test
There are two ways:
use source to do it.
source $<your_file_path> echo $email
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.
Just source the code in the beginning of your code:
. file
or
source file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With