Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Parse a .env (dotenv) file directly using BASH
# Pass the env-vars to MYCOMMAND
eval $(egrep -v '^#' .env | xargs) MYCOMMAND
# … or ...
# Export the vars in .env into your shell:
export $(egrep -v '^#' .env | xargs)
@wieczorek1990
Copy link

wieczorek1990 commented Jan 21, 2022

I wrote my own because was using forbidden symbols in envs.

This basically adds apostrophes so that all variables will be treated as strings. This way you can use your Docker env files and source them with source envs.sh

import sys


def main(input_path, postfix='.sh'):
    with open(input_path, 'r') as file_handle:
        lines = file_handle.readlines()
        envs = {}
        for line in lines:
            try:
                parts = line.split('=')
                name = parts[0]
                value = ''.join(parts[1:]).rstrip('\n')
            except ValueError:
                pass
            else:
                envs[name] = value

    output_path = f'{input_path}{postfix}'
    with open(output_path, 'w') as file_handle:
        lines = []
        for name, value in envs.items():
            line = f'{name}=\'{value}\'\n'
            lines.append(line)
        file_handle.writelines(lines)


if __name__ == '__main__':
    # Passes first argument as input path.
    main(sys.argv[1])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment