I'm trying to get su to source /home/ghost/.bashrc, but it doesn't seem to load the contents:

$ su -l -c 'source /home/ghost/.bashrc; nvm' ghost
-su: nvm: command not found

I use nvm to manage Node versions. Nvm is normally sourced by the ghost user in /home/ghost/.bashrc:

# in /home/ghost/.bashrc
export NVM_DIR="/home/ghost/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm

I found from these questsions that putting the nvm init code in /home/ghost/.profile makes nvm available to su -l since it starts a login shell.

I still can't figure out why I can't source the file explicitly. Can anybody tell me why?

  • It's nvm.sh, not nvm. Also you don't need -l: su -c 'source /home/ghost/.bashrc; nvm.sh' ghost – kos Feb 6 '16 at 17:49
  • Pretty sure it's supposed to be nvm. At least, that's what they suggest in their README. EIther way, that command doesn't work either unless I put the nvm init stuff in ~/.profile. For some reason I can't source anything explicitly from su -c. – beane Feb 6 '16 at 18:08
  • 1
    How did you determine that the failure to find nvm means that the file is not being sourced? Where is nvm, and does /home/ghost/.bashrc add that location to the PATH? if so, how? – steeldriver Feb 6 '16 at 18:32
  • Ah I see, sorry, I read "This loads nvm" and thought "$NVM_DIR/nvm.sh" was used to start it automatically. – kos Feb 6 '16 at 18:52
  • Please, add output of this to your question: ls -ld /home/ghost/.nvm/nvm.sh – Cyrus Feb 6 '16 at 19:53

The file was getting sourced, but execution was stopped when it reached this case statement, which will only continue if it is being sourced in a shell in interactive mode.

case $- in
    *i*) ;;
      *) return;;

The variable $- represents the flags with which the current shell was initialized. If it doesn't see i (the flag for interactive mode), the code will return. Because the shell wasn't being run in interactive mode, source .bashrc stopped when it reached that case statement.

For reference, the output of echo $- when using a normal interactive shell is himBH. The output of su -l -c 'echo $-' ghost, however, I see hBc.

Moving the nvm lines above that statement solved the problem, as did putting them into a clean .profile or .bashrc.

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.