I recently read an answer here that included the following advice:
However, as a rule, ⚠️you should not
source ~/.zshrc
. Depending on what's in your dotfiles, this can lead to all sorts of problems.
I asked the OP for an example of why this could be a problem and was told:
Because it's been sourced already when your shell started up and the order in which commands are run can matter. As a simple example, put
ls() { command ls -x "$@" }; alias ls='ls -AF'
into your.zshrc
file, restart your shell, thensource ~/.zshrc
. Now you get an errorzsh: defining function based on alias ls'
. And that's only a fairly innocuous example. Things can get much more hairy than that
That does sound plausible, although I couldn't reproduce that error with zsh
. Despite its plausibility, I am having trouble imagining a situation where this could cause any serious issues and those issues would not also occur when opening a clean new session. Worst case scenario I can think of is getting an error message, and I don't even know how to make that happen either.
So, is there good reason to avoid manually sourcing a shell's rc
file after making changes to it so that the changes are imported into the current shell session?
I know I have been doing this with bash
for many years: I will regularly add a function, or make a change to my ~/.bashrc
and then . ~/.bashrc
to source it. Are there really cases where that could cause any serious problem? I suppose we can find some edge cases, but are those enough to justify such an empathetic warning? Perhaps there's something specific to zsh
that I haven't encountered as a bash
user?
I am interested in answers covering any bourne-family shell (bash, sh, zsh, ksh etc.).
grep
somewhere early on in.bashrc
, and then later you define a customgrep
function, and the change in behaviour might break that something when you source.bashrc
again in unexpected ways - but you wouldn't see anything wrong in a clean new session).grep
function can't affect any use ofgrep
in.bashrc
before its defined. For a concrete example, say you have something likefoo=$(grep -m1 A /etc/os-release)
grep () { command grep -H "$@"; }
PS1="$foo %u $"
. The value of$foo
will change after you source it again..zshrc
file, incorporating any changes to it in the current environment should be as easy as using the interactive shell to modify the environment in the appropriate way, mirroring the change in the startup file. Also, suggesting to others to source the file is irresponsible. You don't know what manner of things their script is doing.