dotenv, but just 1 line of shell

kwstannard profile image Kelly Stannard Updated on ・1 min read


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.



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 % "$@"; }
$ 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

Posted on by:

kwstannard profile

Kelly Stannard


Developer. Design pattern enthusiast. Tilting at Agile practices.


Editor guide

Fixed for values with spaces.