I want to write a init script that should basically run
nvm use v0.11.12 && forever start /srv/index.js
as the user webconfig
. nvm
is a shell function that is declared in ~webconfig/.nvm/nvm.sh
, which is included via source ~/.nvm/nvm.sh
in webconfig
's .bashrc
.
I tried the following:
sudo -H -i -u webconfig nvm
echo "nvm" | sudo -H -i -u webconfig
but they fail with
-bash: nvm: command not found
-bash: line 1: nvm: command not found
When I run sudo -H -i -u webconfig
and enter nvm
manually in that shell, it works. What am I doing wrong?
Best Answer
The problem here, as is so often the case, is about the different types of shell:
When you open a terminal emulator (
gnome-terminal
for example), you are executing what is known as an interactive, non-login shell.When you log into your machine from the command line, or run a command such as
su username
, orsudo -u username
, you are running an interactive login shell.So, depending on what type of shell you have started, a different set of startup files are read. From
man bash
:In other words,
~/.bashrc
is ignored by login shells. Since you are using the-i
option tosudo
, the startup files for the user's login shell are being read (fromman sudo
):So, what you can do is
Define the function in the user's
~/.profile
or~/.bash_profile
instead. Bear in mind that~/.profile
is ignored if~/.bash_profile
exists. Also keep in mind that~/.bash_profile
is bash-specific so I would use.profile
instead, just make sure that~/.bash_profile
does not exist.Source
~/.nvm/nvm.sh
from~/.profile
.