I have a Vagrant machine, but I cannot change the vagrant configuration.

I want to access to the vagrant machine, switch to superuser and then launch some commands. How can I do this in one shot or in a script file?

By now I'm able to access to vagrant as su with this command:

vagrant ssh -c "cd /opt/path && sudo su"

But if I launch other commands like this:

vagrant ssh -c "cd /opt/path && sudo su -c \"nvm use 10.16.0\""

I have this log:

bash: nvm: command not found
Connection to closed.

A simple echo, instead, works fine. this command:

vagrant ssh -c "cd /opt/path && sudo su -c \"echo \"hello\"\""


Connection to closed.
  • It looks like a basic $PATH issue: where is located the nvm binary ? Did you tried by specifying the full path to it ? (for example, if nvm is under /usr/local/bin, then call /usr/local/bin/nvm).
    – binarym
    Jan 9, 2020 at 13:48
  • Is nvm installed for the root user or for the vagrant user? The problem is that normally the nvm command is set from your .bashrc file Jan 9, 2020 at 13:58
  • @binarym this is my $PATH output: /root/.nvm/versions/node/v10.16.0/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/lib/jvm/jre-1.8.0 I try using /root/.nvm/nvm but doesn't work
    – ufollettu
    Jan 9, 2020 at 14:28
  • @user2563661 for the root user
    – ufollettu
    Jan 9, 2020 at 14:30

1 Answer 1


The issue is probably that the nvm command is set from the root user's .bashrc file. When you run su user the user's environment will not be used except for HOME and SHELL and additionally USER and LOGNAME for non-root users.

Normally, you would use the --login flag of su to use the user's environment (or just - for short). However, this is not enough when you want to source the .bashrc file since .bashrc will be sourced for interactive shells only.

I would suggest trying to move the nvm code from /root/.bashrc to /root/.bash_profile and run the command as vagrant ssh -c "cd /opt/path && sudo su --login -c \"nvm use 10.16.0\"". So whatever nvm added to .bashrc, e.g.:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

just move to /root/.bash_profile

Just as a side note, I don't think it is the best idea to install nvm for the root user. It would be much safer to install it for vagrant.

  • Thnak you, but for entrerprise policy I cannot change any internal vagrant configuration, so I need to workaround this limitation in another way
    – ufollettu
    Jan 9, 2020 at 15:43
  • @ufollettu I think you could also run the lines of nvm code from .bashrc manually before running nvm, e.g., sudo su -c "export NVM_DIR="/root/.nvm" ; ... ; nvm use 10" Jan 9, 2020 at 17:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .