0

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?

beane
  • 11
  • It's nvm.sh, not nvm. Also you don't need -l: su -c 'source /home/ghost/.bashrc; nvm.sh' ghost – kos Feb 06 '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 06 '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 06 '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 06 '16 at 18:52
  • Please, add output of this to your question: ls -ld /home/ghost/.nvm/nvm.sh – Cyrus Feb 06 '16 at 19:53
  • @steeldriver - the code in the bashrc loads nvm. Since I can't use nvm, bashrc wasn't sourced. When I added echo statements to the bashrc they also failed to print. I'll edit the question to add some more info. – beane Feb 06 '16 at 23:02
  • @all - figured it out. The default /home/ghost/.bashrc had code that halted execution if the shell wasn't being run in interactive mode. Starting from a blank .bashrc or moving nvm to the stop solved the problem. Thanks for all your help! – beane Feb 06 '16 at 23:10

1 Answers1

1

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;;
esac

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.

beane
  • 11