Of course, source <file>
is a Bash command - it uses the source
builtin to run script <file>
in the context of the current shell rather than in a child process, thus allowing commands in <file>
to change the current shell's environment, such as in terms of the working directory (using cd
).
Using source
, or its alias .
, is (ultimately) the only way to achieve that.
If your intent is not to have to invoke <script>
explicitly with source
, you have two options, both of which are best defined in your Bash profile, ~/.bash_profile
(since you're on OS X; on Linux, use ~/.bashrc
[1]):
I'll assume that your script is /path/to/foo
, and that you want to invoke it sourced as just foo
:
- Option 1: Define an alias:
alias foo='source "/path/to/foo"'
- Option 2: Define a function:
foo() { source "/path/to/foo"; }
Both aliases and functions execute in the current shell, allowing you to effectively hide the source
call behind a single command; aliases are generally a little easier to define, but functions offer more flexibility.
By virtue of the alias / function being defined in your Bash profile, which itself is implicitly sourced, the commands in /path/to/foo
will affect your interactive shells' environment.
Note: Either definition of foo
will only be available in interactive shells (those that (automatically) source ~/.bash_profile
).
Additional steps would be needed to make foo
work inside non-sourced scripts as well, but at that point you should ask yourself whether you're obscuring things by not making the fact that /path/to/foo
is getting sourced explicit.
If you're writing a script that must be sourced for distribution to others:
Install the sourcing command in the user's shell profile / initialization file (as described above) on installation of your script.
- If there is no installation process (and also to enable on-demand installation in general), implement a command-line option for your script such as
i
(--install
) that performs this installation on demand.
Preferably, also implement an uninstallation option.
Either way, build logic into the script so that it refuses to run when run without sourcing, and have the error message contain instructions on how to install sourcing.
A real-world implementation of the above - although more elaborate due to being multi-shell - is my typex utility; source code here.
[1] On OS X, Bash instances started by Terminal.app are login shells, which means that the only (user-specific) file that is automatically sourced on startup is ~/.bash_profile
.
By contrast, on most Linux systems Bash instances are non-login shells, where only ~/.bashrc
is automatically sourced.
While it is common practice to source ~/.bashrc
from one's ~/.bash_profile
, this has to be configured manually and therefore cannot be relied upon blindly.