无法从/etc/profile中获取GoLang的环境变量。

huangapple go评论88阅读模式
英文:

Can't get environment variable from /etc/profile in GoLang

问题

我在/etc/profile中设置了一些环境变量,我可以从bash中访问它们,但是出于某种原因,我无法从Go中获取它们。

/etc/profile:

...
TEST_ENV=test_me

我可以从bash中访问它:

echo $TEST_ENV
test_me

但是我无法从Go中访问这个变量:

os.Getenv("TEST_ENV") // 返回 ""

如果我使用以下命令列出可用的环境变量:

os.Environ()

我找不到我要找的变量,但有一些变量可能有所帮助:

SHELL=/bin/sh
USER=root
LOGNAME=root

我猜我的问题与不同的会话和shell有关,所以我甚至尝试运行:

exec.Command("source /etc/profile")

然后在获取变量,但仍然返回空值。

你能给我一些建议吗,如何获取如果它们在/etc/profile中设置的环境变量?我更希望从那个文件中获取它们,但如果必要,我也可以将变量放在其他地方。

英文:

I've set some environment variables in /etc/profile, I can access them from bash, but for some reason I cant get them from Go.

/etc/profile:

...
TEST_ENV=test_me

I can access it from bash:

echo $TEST_ENV
test_me

I can't access this variable from GO

os.Getenv("TEST_ENV") // returns ""

If I list the available environment variables with

os.Environ()

I don't see the variable I'm looking for, but there a few variables that might help:

SHELL=/bin/sh
USER=root
LOGNAME=root

I guess my problem is related to different sessions and shells, so I even tried running

exec.Command("source /etc/profile")

and get the variables after, but it still returns nothing.

Can you give me some tips how to get environment variables if they're set in /etc/profile? I'd prefer getting them from that file, but if necessary, I can put the variables in a different place as well.

答案1

得分: 5

当你在bash中设置一个环境变量时,默认情况下它不会被导出。只有导出的环境变量才会传递给由shell创建的进程(即你运行的程序)。尝试使用export TEST_ENV=test_me命令。

英文:

When you set an environment variable in bash, by default it isn't exported. Only exported environment variables are passed along to processes created by the shell (i.e., programs that you run). Try export TEST_ENV=test_me.

huangapple
  • 本文由 发表于 2017年2月7日 22:13:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/42092069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定