DEV Community

Kelly Stannard
Kelly Stannard

Posted on • Edited on

2

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (1)

Collapse
 
kwstannard profile image
Kelly Stannard

Fixed for values with spaces.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more