dotenv, but just 1 line of shell
KW Stannard

KW Stannard @kwstannard

About: Developer. Design pattern enthusiast. Tilting at Agile practices.

Joined:
Sep 9, 2019

dotenv, but just 1 line of shell

Publish Date: Sep 25 '19
7 1

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

Comments 1 total

Add comment