Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a sourced shell function?

Tags:

bash

nvm

In the nvm README.markdown it says

Please note that which nvm will not work, since nvm is a sourced shell function, not an executable binary.

What I found is the nvm install process will update the .bashrc with

[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm

Somehow this makes the nvm command available to the shell. My question is what is a "sourced shell function" and what exactly does the command nvm execute?

like image 829
user3885927 Avatar asked Oct 20 '16 22:10

user3885927


1 Answers

This verbiage is sloppy. nvm is simply a shell function defined by sourcing the file in which that function is defined. That doesn't change the function in any qualitative way: It would be the same function, with all the same behaviors, if you'd typed it in by hand, so applying "sourced" as a modifier is a bit misleading; it would be more accurate to say that nvm.sh is a sourced script which defines a shell function named nvm.


As for the specific syntax:

. somefile

is the more portable way to write

source somefile

...which performs the actions in somefile within the current shell, as opposed to within a separate shell run as a subprocess.

Thus, sourcing a script can modify your current interpreter -- setting variables, changing its working directory, and, yes, defining aliases and functions -- in ways that executing an external program cannot.


To clarify: If you ran bash somefile, then any functions defined by somefile exist only for the duration of that particular copy of bash -- when it exited and returned you to your prompt, functions defined in somefile would no longer be available. By contrast, when you source somefile, because the contents of somefile are executed in your current shell instance, those contents are able to persist.

like image 161
Charles Duffy Avatar answered Oct 14 '22 09:10

Charles Duffy