0

I try to run nvm as a different user from a bash script. It is installed already and the NVM_DIR environment variable is set in /home/user/.bashrc:

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

Using plain su works:

root@ubuntu:~# su user
user@:/root$ echo $NVM_DIR
/home/user/.nvm

Trying the same thing with su -c does not work though:

root@ubuntu:~# su user -c 'echo $NVM_DIR'

root@ubuntu:~#

How can I use environment variables with su -c?

2

The behavior you're observing is because su -c 'command' does not execute command in an interactive shell.

Since su doesn't appear to provide an option to do so, probably the cleanest way to do what you want is to move the NVM environment variables into a separate file, called nvm_envs say, and source that explicitly e.g.

su user -c '. ~/nvm_envs && echo $NVM_DIR'

If you want interactive bash shells to have the same environment, source the same file from your .bashrc file e.g.

if [ -r "$HOME/nvm_envs" ]; then
  . "$HOME/nvm_envs"
fi

(This is exactly how the default .profile file conditionally sources the user's env_vars file: you could use that file instead if you prefer.)

| improve this answer | |
  • What about su - user -c 'echo $NVM_DIR'? With the additional -? – PerlDuck Feb 14 '19 at 18:52
  • @PerlDuck that will force it to use a login shell, which - if the user's login shell is bash, at least with the default Ubuntu ~/.profile, will read their ~/.bashrc: however, the default ~/.bashrc basically just exits if the shell is non-interactive. It would work if the environment variables were defined before the interactivity test - but that feels kind of wrong somehow. – steeldriver Feb 14 '19 at 19:05
  • @PerlDuck I also tried that, did not work unfortunately. – thesys Feb 14 '19 at 19:14
  • @thesys Okay. Was just an idea. But steeldrivers explanation and suggestion seems reasonable. – PerlDuck Feb 14 '19 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.