1

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?

3

2 Answers 2

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.)

4
  • What about su - user -c 'echo $NVM_DIR'? With the additional -?
    – PerlDuck
    Feb 14, 2019 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. Feb 14, 2019 at 19:05
  • @PerlDuck I also tried that, did not work unfortunately.
    – Bobface
    Feb 14, 2019 at 19:14
  • @thesys Okay. Was just an idea. But steeldrivers explanation and suggestion seems reasonable.
    – PerlDuck
    Feb 14, 2019 at 19:22
-1

Try:

sudo -i -u user sh -c 'echo $NVM_DIR'
1
  • 2
    You used double quotes, so NVM_DIR is expanded by your current shell, not sh.
    – muru
    Jun 30, 2021 at 14:26

You must log in to answer this question.

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