DEV Community

Kelly Stannard
Kelly Stannard

Posted on • Updated on

dotenv, but just 1 line of shell

update

The shell script below breaks on significant edge cases due to how inconsistent bash is. The following ruby script works for all cases I know about. This is all for personal fun though. Dotenv has years of fixing edge cases.

https://dev.to/kwstannard/dotenv-but-7-lines-of-ruby-19lp

=======

This can probably replace dotenv in most situations and is also language agnostic.

For BSD(macos) xargs
de() { [ -f .env ] && <.env grep -v "^#" | tr '\n' ' ' | xargs -J% env % "$@"; }
For GNU xargs
de() { [ -f .env ] && <.env grep -v "^#" | tr '\n' ' ' | xargs -I% env % "$@"; }
Examples
$ echo hello=world > .env
$ echo $hello        # this is to prove $hello doesn't exist normally
>
$ de bash -c 'echo $hello'
> world
$ de ruby -e 'puts ENV["hello"]'
> world
$ de clojure -e '(System/getenv "hello")'
> "world"
$ de python3  -c 'import os; print(os.environ["hello"])'
> world

Discussion (1)

Collapse
kwstannard profile image
Kelly Stannard Author

Fixed for values with spaces.