DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

Shell - load env variables from .env

Sample codes to load environment variables from .env file in sh.

#!/usr/bin/env sh

# Load variables from .env file.
export $(cat ./.env | grep -v ^# | xargs) >/dev/null

# Refer to variables.
echo "KEY_IN_ENV=${KEY_IN_ENV}"
Enter fullscreen mode Exit fullscreen mode

Here is test code, which creates test .env and echo it.

#!/usr/bin/env sh

TEST_KEY1="This value will be replaced."

# Create test .env
cat <<EOF > .env
TEST_KEY1=VALUE1
TEST_KEY2=VALUE2
EOF

# Load .env
export $(cat ./.env | grep -v ^# | xargs) >/dev/null

# Check
echo "TEST_KEY1=${TEST_KEY1}"
echo "TEST_KEY2=${TEST_KEY2}"
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
otumianempire profile image
Michael Otu

So basically this is a script that create a .env file and echos the content??

Collapse
 
takakd profile image
Takahiro Kudo

Yes, you are right. Sorry for the code is not clear, then I fixed it. How about this?

Collapse
 
otumianempire profile image
Michael Otu • Edited

Assume I have no knowledge of bash, which I don't extensively. I know you have done your best but if there was some texts or comments explaining the lines, it will help understand the code better. Also resources too. Thanks

Thread Thread
 
takakd profile image
Takahiro Kudo

Oh, I understand. I'll reconsider the content. Thank you for your feedback.

Collapse
 
otumianempire profile image
Michael Otu

I wish the was more information to this.. thank in advance

Collapse
 
mrashad10 profile image
Mohamad Rashad

Thanks, I needed this