DEV Community

Kelly Stannard
Kelly Stannard

Posted on • Edited 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 % "$@"; }
Enter fullscreen mode Exit fullscreen mode
For GNU xargs
de() { [ -f .env ] && <.env grep -v "^#" | tr '\n' ' ' | xargs -I% env % "$@"; }
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
kwstannard profile image
Kelly Stannard

Fixed for values with spaces.