DEV Community

loading...

Shell - load env variables from .env

takakd profile image Takahiro Kudo ・1 min read

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

Discussion (5)

pic
Editor guide
Collapse
otumianempire profile image
Otu Michael

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

Collapse
takakd profile image
Takahiro Kudo Author

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

Collapse
otumianempire profile image
Otu Michael • 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 Author

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

Collapse
otumianempire profile image
Otu Michael

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