I'm trying to run a simple command from an init.d script and I'm troubleshooting why the command doesn't work when I run it from my init.d script but works when I run it as my user.
Can someone explain why when I run nvm --version
as my logged in user it shows a value, but when I su
to my user it does not know what nvm
is? This is ultimately the root cause of my init.d script not working I believe.
$ whoami
someuser
someuser@node-server1:/var/www/dev$ nvm --version
0.18.0
someuser@node-server1:/var/www/dev$ su - someuser -c "nvm --version"
Password:
-su: nvm: command not found
I noticed this in my .bashrc:
export NVM_DIR="/home/someuser/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
Do I somehow need to run this as a command in my init.d script or when I su
to a user?
This is because the 'someuser' user's
$PATH
does not have the path where thenvm
binary is located. To be able to use the commandnvm
you need to add the location ofnvm
binary to that user's path.Do this:
Run
which nvm
as the user for whomnvm
command is currently availble. If will show you where thenvm
command is located. For example, ifwhich nvm
gives you/usr/local/nvm/bin/nvm
, then you have to add/usr/local/nvm/bin
to the path of the user wherenvm
is not currently available. For that, add the following line in the new user's .bashrc.export PATH=$PATH:/usr/local/nvm/bin
Once, its done, log out, log back in, or
source
the .bashrc file and thenvm
command will be available for the new user.For example: If user 'abc' does not have nvm available, add the
export PATH...
line to /home/abc/.bashrcFrom the NVM documentation:
So, yes, in order to be able to use nvm, you must first "activate" it before invoking it.
Where is located the nvm program? To find this out, you can type
whereis nvm
. It looks like this directory is added to the path somewhere inside your .bashrc file.What you have to know is that "su -c" runs a non-interactive shell. You can check this by looking into $- variable content :
The 'i' means the shell is currently interactive. Well, in ubuntu, you can notice that your .bashrc file starts with those few lines:
This means that this file isn't sourced if the $- variable doesn't contain an 'i', i.e while in an non-interactive shell.
You have two possible workarounds:
1- Run nvm with sudo command instead of su:
Note that because of sudo's behaviour, you mustn't use quotes.
2- Use nvm's full path to the binary and source the required file:
Using
nvm
instead of its full path/path/to/nvmdir/nvm
may be sufficient if $HOME/.nvm/nvm.sh is the one updating your $PATH.