Rajesh
Rajesh

Reputation: 24905

Setting system variable using Node

I have been working on a node script that does the installation of external dependencies and was wondering if its possible to set the PATH variable using Node.

For example, If I want to install Go using script, I can execute command brew install Go and this works but when I do export GOPATH=$PATH, this is never set.

I also tried using process.env but this also does not work. Also my assumption with process is that it must run in a sandbox. So it will not update/ set anything outside.

So the question is, can I do this? If yes, how?

Upvotes: 0

Views: 209

Answers (1)

slebetman
slebetman

Reputation: 113878

It is not possible in any programming language. At least on Unix (BSD, MacOS, Illumos etc.) and Linux, I'm not sure about Windows.

As a security feature, Unix processes are designed such that they cannot touch the environment of their parent's process. Only the parent process can influence the environment of their children.

When you are on a command line you are running a shell program (either Bash or Korn Shell or TCSH or Fish etc.). When you execute something on the command line such as a node.js script or Google Chrome or Minecraft these programs will be the children to your shell program. On Unix and Linux these child programs inherit their parent's environment.

That is why you can export environment (global) variables and your programs can access them. However, this relationship is one-way and it was designed that way on purpose.

You may notice that in shell scripts you can "save" commands to set environment variables in a file. For example in Bash you sometimes see people do this:

# variables.sh

export HELLO "World"

However, this will not work if you execute the script as a script:

$ bash variables.sh
$ echo $HELLO
                   <--------------------- nothing is displayed here
                                          the variable is not exported

You sometimes see people do this instead:

$ . variables.sh
$ echo $HELLO
World

And you may wonder how that works. Well.. in some shell languages the dot command imports the script instead of executing the script as a separate process. Think of it like import or require() in javascript.

Of course, Bash does not understand javascript syntax. It also does not understand C++ or Java or Ruby or PHP. It only understands Bash syntax.

So the longer answer is it is not possible in any programming language except for the language of the shell you are using (eg. if you are using Fish you need to write a script in Fish syntax or if you are using Ksh you need to write a script in Korn syntax).

Upvotes: 1

Related Questions