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?
Try with below command:-
Do not use
ls
first, if it works then only try withls
Consider defining a shell function wrapper:
...thereafter:
...or...
To explain the above logic:
-l
and-i
arguments to bash ensure that dotfiles for the target user (in this caseroot
) are run, which appears to be necessary fornvm
'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 thebash -c
script's context refers to the full set of arguments (starting at$1
, so skipping the_
) passed to the shell after the-c
.I found a solution, even when this is not a beautiful solution in my opinion.
I had a misunderstanding, suspecting
nvm.sh
gets called onnvm
, directly. In fact,nvm.sh
contains several shell functions that are loaded in the user shell environment, but not in the root shell environment.First, I enabled the root user and logged it in at the terminal. Then I had to
source
the contents of thenvm.sh
to define the functions at the su environment. Then I could run the command and the su found it:Works!