I need to convert each property of a properties file to a environment variable:

I mean, guess this property file:

mongo.databaseName = test


I'd like to create them as environment variables as

export MONGO_PORT=27017
export MONGO_HOST=
export BO_URL_JWT=https://localhost:8089/token

Any tool or script in order to get this?

I'm using ubuntu 18x + zsh


Here is a short script that can do this:


cut -d= -f 1 props.txt  | tr '[:lower:]' '[:upper:]' | tr '.-' '_' > $tmp1
cut -d= -f 2 props.txt > $tmp2

paste -d= $tmp1 $tmp2 > output.props

sed -i 's/ *= */=/' output.props
sed -i 's/^/export /' output.props

rm $tmp1 $tmp2

This script works in the following manner. Two temporary files are generated using mktemp. The input properties file is split on the '=' character and the two respective fields are sent to these two files.

On the first field (the property name), the tr command is applied twice. Once for lowercase-to-uppercase conversion, once for changing the special characters to an underscore. The field values are only written to the temporary file after these changes.

Once the processing is done, the paste command is used to the put the fields back together into a single file, output.props. Then, two sed commands are used. The first one removes any space characters around the '=' character, which would otherwise be a syntax error for the export command. The second sed command is used to prefix the string 'export ' to each line. Finally, the two temporary files are cleaned up.

Sample output:

$ cat output.props
export MONGO_PORT=27017
export MONGO_HOST=
export BO_URL_JWT=https://localhost:8089/token

Once the output file is generated, source it to actually set the variables in the environment. One of the two following syntaxes may be used for this:

. output.props
source output.props
  • Could you show on post, how to populate generated output.props to env variables then? – Jordi Jan 29 at 13:29
  • @Jordi I've edited my answer with this information. Do note that I have added one more sed command to clean up the spaces from the input as well. – Haxiel Jan 29 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.