Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to load both .env file and the os environment variables in golang

err := godotenv.Load(".env")
if err != nil { panic(err.Error()) }

shell := os.Getenv("SHELL")
fmt.Println(shell)

I set the SHELL=/bin/zsh in my .env file but it seems the os first look for the given key in the os environment variable list and then It checks the .env file . is there a way to separate these two ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes there is a way to solve this problem .
the github.com/joho/godotenv has a function called Read() . you can load your .env file into a map data structure .

envFile, _ := godotenv.Read(".env")

envFileShell = envFile["SHELL"]
fmt.Println(envFileShell) // will be /bin/zsh (what you set in .env file)

osShell := os.Getenv("SHELL") 
fmt.Println(osShell) // will be whatever it is set in your operating system 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading