Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute "sudo nvm"?

On my Mac, I want to migrate some packages that require su rights to another node version.

I used homebrew to install nvm and now I need to execute sudo nvm or --reinstall-packages will fail.

me@MacBook:~$ sudo nvm
sudo: nvm: command not found
me@MacBook:~$ sudo node -v
v5.4.1
me@MacBook:~$ sudo npm -v
3.3.12
me@MacBook:~$ nvm ls
->       v5.4.1
         v9.6.1
         system
default -> 5.4.1 (-> v5.4.1)
node -> stable (-> v9.6.1) (default)
stable -> 9.6 (-> v9.6.1) (default)
iojs -> N/A (default)
lts/* -> lts/carbon (-> N/A)
lts/argon -> v4.8.7 (-> N/A)
lts/boron -> v6.13.0 (-> N/A)
lts/carbon -> v8.9.4 (-> N/A)

I think the command cannot be found, because sudo is looking in different paths. I've found nvm.sh in /usr/local/opt/nvm, however:

sudo /usr/local/opt/nvm/nvm.sh ls

returns nothing.

Even

/usr/local/opt/nvm/nvm.sh ls

returns nothing, so I suspect this is the wrong shell script.

How can I call nvm with sudo, explicitly?

like image 573
Martin Braun Avatar asked Jun 14 '26 00:06

Martin Braun


1 Answers

Consider defining a shell function wrapper:

nvmsudo() { sudo bash -lic '. /usr/local/opt/nvm/nvm.sh && nvm "$@"' _ "$@"; }

...thereafter:

nvmsudo --version

...or...

nvmsudo install 5.4.1 --reinstall-packages-from=9.6.1

To explain the above logic:

  • Using the -l and -i arguments to bash ensure that dotfiles for the target user (in this case root) are run, which appears to be necessary for nvm's correct operation.
  • bash -c's immediate next argument must be a script. The arguments following that become $0, $1, etc. in the context where the script is executed.
  • "$@" in the function context refers to the full set of arguments to the function.
  • "$@" in the bash -c script's context refers to the full set of arguments (starting at $1, so skipping the _) passed to the shell after the -c.
like image 182
Charles Duffy Avatar answered Jun 16 '26 15:06

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!