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
CodePudding user response:
$ type nvm
nvm is a shell function from /home/jkugelman/.nvm/nvm.sh
A script runs in a child process and cannot change environment variables in the parent. A shell function, on the other hand, runs in the same shell and can manipulate the environment.
If you want to see exactly what it's doing use declare -pf
(print function) or which
:
$ declare -pf nvm
nvm () {
# code snipped
}
CodePudding user response:
The command is likely a function. For example:
#!/bin/bash
function set_nvm() {
PATH="$1:$PATH"
}
Source the above file so that the function is available in the shell. This can be done in your .bashrc
so you don't have to manually do it every time:
$ . test.sh
Then you can call the function as it were a command:
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
$ set_nvm /tmp
$ echo $PATH
/tmp:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin