Search code examples
bashenvironment-variablesdotenvdash-shell12factor

How to source a dotenv (.env) file in dash?


There are a lot of examples here how to source a dotenv file in bash but has anyone one a method that achieves the same with dash (which is the default shell for minimal Debian installations)?

The solution should look like this:

$ some foo my-command-using-env-vars

e.g.

$ env $(cat .env) my-command-using-env-vars

And it is important that the solution supports multiline values with spaces like:

SSH_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nfoo\nbar\baz"

and special characters like hash within quotes:

SPECIAL="foo#bar"

Solution

  • It seems that your problem is not so much that you're using dash but that you want to support \n escapes. The following works in dash and supports \n escapes:

    eval "$(echo $(cat .env))" my-command-using-env-vars
    

    That's because unlike in bash the built-in echo in dash supports backslash escapes even without the -e option. The following works in both bash and dash, provided that the non-built-in, system echo supports the -e option:

    eval "$(env echo -e $(cat .env))" my-command-using-env-vars
    

    Note that both approaches will also handle other backslash escapes (either POSIX or GNU), possibly in a different way than you expect.

    Some technical notes:

    $(cat .env)
    

    performs Field Splitting, converting any newline in file .env into spaces.

    "$(env echo -e ...)"
    

    expands backslash escapes regardless of the current shell by invoking echo -e via env. The double quotes disable field splitting, so that newlines are preserved.