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)?
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 exec
ed), 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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With