What is the best way to source
a config file in bash and import their variables/contents in a script?
Let's say, I have a config file called /path/index.conf
, which is like:
VAR1=
VAR2 = 1
VAR3=A&C
#comment
PASSWORD=xxxx
EMAIL=abc@abc.com
I am writing a shell script that will do the following:
1) If the config file does not exist, then the script will create the config file with default values.
2) If any of the variable's value is missing, the script will replace those specific variables with default values. For example VAR1=
value is missing and it should be replaced with VAR1=0
3) The script should skip comments and whitespaces (for example, VAR2 = 1
some whitespaces), and complain if any of the lines contains $,%, and & character
This what I have done so far:
#!/bin/sh
#Check the config file
source_variables () {
source /path/index.conf
#TODO: if the file does not exist, create the file
#TODO: file exists, but missing some variables, fill them with default values
test -e /path/index.conf
if test "$VAR1" = "0" ; then
echo "VAR1 successfully replaced "
fi
#TODO: If any variable contains $,%, and & (for example VAR3). Flag it and return 1.
#import all the variables and declare them as local
local var_a = $VAR1
local var_b = $VAR2
# ...etc
return 0 #checking successful
}
I am learning bash scripting, and I understand that my approach is incomplete and might not be the best practice out there. Can anyone help me?