How to extract an ini section using sed and export them as environment variables
Assume that you have an ini configuration file and you need to export various sections as environment variables to be used from your…
Assume that you have an ini configuration file and you need to export various sections as environment variables to be used from your script, to do this you can use a handy oneliner! follow me in this article in order to explain you how it works, else if you need just the one-liner and you can copy paste it and modify the configuration file accordingly.
The one-liner
eval $(sed -n '/^\[database\]/,/^\[/p' config.ini | sed '$d' | sed '/^\s*#/d;/^\s*$/d' | awk -F= '{gsub(/ /,""); if($1 && $2) print "export " toupper($1) "=\"" $2 "\"" }')How it works
sed -n '/^\[database\]/,/^\[/p' config.ini | sed '$d': Extracts the[database]sectionsed '/^\s*#/d;/^\s*$/d': Removes comments and empty lines.awk -F=: Processes key-value pairs.gsub(/ /,""): Removes spaces.print "export " toupper($1) "=\"" $2 "\"": Converts keys to uppercase and prints them asexportcommands.eval $(...): Executes the generatedexportcommands.
Example:
If your config.ini looks like this:
[database]
host = localhost
port = 5432
user = admin
password = secretRunning the one-liner will export:
export HOST="localhost"
export PORT="5432"
export USER="admin"
export PASSWORD="secret"Conclusion
I hope this short article was helpful and simplify your work to read configuration files for your scripts!