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…

How to extract an ini section using sed and export them as environment variables
Photo by Daria Averina on Unsplash

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] section
  • sed '/^\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 as export commands.
  • eval $(...): Executes the generated export commands.

Example:

If your config.ini looks like this:

[database] 
host = localhost 
port = 5432 
user = admin 
password = secret

Running 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!