3

As you can see below, I set an environment variable FOO, but when I execute console.log on the next line, it's undefined. If I set it on the same line where I execute console.log, it is present. Why is the behaviour as such?

$ FOO="123"
$ echo $FOO
123
$ node -e "console.log(process.env.FOO)"
undefined
$ FOO="123" node -e "console.log(process.env.FOO)"
123

Node version: 6.6.0

Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141

1 Answers1

5

If you want to set the environment variable for the current terminal session, you need to use EXPORT

So, this code will work

export FOO=123
node -e "console.log(process.env.FOO)"
123

EXPORT makes the assignment visible to subprocesses. Check this thread for more details

ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
  • Thank you very much! The code works great, but for the benefit of future readers it would be great if you could explain what's the reason why this needs to be done. – Yangshun Tay Jun 07 '17 at 09:02
  • 1
    Yes I can, but I think the link provided by the community ([What does “export” do in shell programming?](https://stackoverflow.com/questions/7411455/what-does-export-do-in-shell-programming) ) does it better than I am able to do it. – ThomasThiebaud Jun 07 '17 at 09:06
  • I get that, but I had to scroll all the way down to the bottom on that thread to find the explanation :( – Yangshun Tay Jun 07 '17 at 09:08
  • 1
    I added one more line and a link to the other thread – ThomasThiebaud Jun 07 '17 at 09:11