Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set environment variable with shelljs

I'm trying to set an env variable in node with shelljs

so here's the psudo code:

const shell = require('shelljs');

shell.exec('export MM=2');
shell.exec('echo $MM');

but this does not printout the value of MM

Any suggestions on how to set an env variable through node with export (execute bash command)?

like image 941
Mahyar Avatar asked Mar 19 '18 21:03

Mahyar


1 Answers

Are you familiar with how environment variables work in general? The wikipedia article has a good high level summary here: https://en.wikipedia.org/wiki/Environment_variable

One of the more unique things about environment variables is how they behave across process boundaries. Each process has its own set of environment variables. You can modify the environment variables in your own process without any issues. Whenever you spawn (fork + exec) a child process, it inherits your set of environment variables. If you are the child process (the process that got execed), you can not set the environment variable of your parent process.

You might realize now that if process A creates a child process B, and B modifies the environment variables, A will not see the changes.

So shells handle this specially. export is a shell-built in. In other words, bash (or any other shell) will not actually execute an export command by invoking a binary. Instead the shell will understand what export needs to do and do that directly, adjusting the environment variables in the shell process, not in a separate child process. Then any further command that gets run will inherit the (updated) environment variables from the shell.

You need to do the same.

shelljs provides a separate object, env, for this purpose:

shell.env["MM"] = "2";
like image 169
omajid Avatar answered Oct 25 '22 22:10

omajid