Set environment variables from command line argument

56 views
Skip to first unread message

Amarjeet Anand

unread,
May 9, 2020, 10:04:46 PM5/9/20
to golang-nuts
Hi

Is it possible to set environment variables while running my app like...

go run -env_var1="val1" main.go


And then access env_var value as -

 os.Getenv("env_var1")

I know, we can access command line arguments in go and set it manually as environment variables. But am asking if there is already some feature like this in the language.

Kurtis Rader

unread,
May 9, 2020, 10:14:48 PM5/9/20
to Amarjeet Anand, golang-nuts
On Sat, May 9, 2020 at 7:04 PM Amarjeet Anand <sarvm...@gmail.com> wrote:
Is it possible to set environment variables while running my app like...

go run -env_var1="val1" main.go

Is there some reason you can't simply do this

    env_var1=val1 go run main.go

Or this

    env env_var1=val1 go run main.go

if your shell doesn't support the POSIX shell syntax for temporary modification of the environment a command inherits?

--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank

Amarjeet Anand

unread,
May 9, 2020, 10:17:54 PM5/9/20
to Kurtis Rader, golang-nuts
It worked. Exactly what I was looking for.
Thanks a lot. 
Reply all
Reply to author
Forward
0 new messages