How to affect a parent process environment in Linux?

likithrao

New Member
Joined
Oct 14, 2022
Messages
2
Reaction score
0
Credits
29
I know that a child process cannot directly affect its parent process, HOWEVER, how does a tool like nvm work? It's a CLI tool that can "instantly" switch between nodejs versions, which I think means modifying the PATH somehow to point to a different binary installed on your PC.

By "instantly" I mean that you can open a shell, run nvm use [version], and the version is available to use in the same shell. How can a script change the PATH of the shell it's run on?

I've been trying to follow the source code but I'm stumped
 
Last edited:


G'day @likithrao and welcome to linux.org :)

This will do better under Command Line so I am moving it there.

Good luck

Chris Turner
wizardfromoz
 
@JasKinasis didn't see you there, mate - if you think there is a better spot, sing out.
 
I’m not sure offhand. I’ve never used nvm or node.js either.

But from a quick bit of DuckDuckGo-fu and a quick squint through the nvm source code, it’s changing environment variables like $PATH and $MANPATH to point to a specified version of node.

But it’s not changing anything inside a parent process.

$PATH is a global environment variable.
If you run a script that modifies $PATH, it will affect the environment of the shell/terminal that you’re working in.

It will also affect subsequent shells/terminals that you open.

Other shells that were already open before you ran nvm use will not be affected unless you issue a command to re-load/re-initialise the environment in each of those shells. Like . ~/.bashrc or some-such.
Then $PATH (and the rest of the environment variables) will be reloaded/refreshed in that terminal.

So for example - let’s say you have three terminals already open.
You go into terminal 2 and run nvm use to change the node version. If you now check the node version in terminal 2, it will report whatever version you just selected. Because $PATH was modified.

Likewise, if you open a fourth terminal and query the node version, it will list the version you just selected.

But if you go to terminal 1, or terminal 3 and query the version, it will most likely list the old version, because the environment in those terminals needs to be re-initialised/re-loaded to pick up the change to $PATH. Because each instance of Bash is started with a fresh copy of the environment.

Terminals 1 & 3 were opened around the same time as terminal 2. But even though $PATH is a global environment variable, their copy of $PATH was not affected by the change to terminal 2’s $PATH, which would also affect the global $PATH.

So these older terminals will not be affected unless their environment is reloaded/refreshed…… I think?!
I could be wrong on that though!
 

Staff online

Members online


Top