How to execute “sudo nvm”?

2019-07-09 04:44发布

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?

3条回答
地球回转人心会变
2楼-- · 2019-07-09 05:15

Try with below command:-

sudo -u <username> /usr/local/opt/nvm/nvm.sh

Do not use ls first, if it works then only try with ls

查看更多
Evening l夕情丶
3楼-- · 2019-07-09 05:21

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.
查看更多
劫难
4楼-- · 2019-07-09 05:25

I found a solution, even when this is not a beautiful solution in my opinion.

I had a misunderstanding, suspecting nvm.sh gets called on nvm, 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 the nvm.sh to define the functions at the su environment. Then I could run the command and the su found it:

me@MacBook:~$ su
Password:
root@MacBook:/Users/me$ source /usr/local/opt/nvm/nvm.sh
root@MacBook:/Users/me$ nvm --version
0.33.8

Works!

查看更多
登录 后发表回答