How to run "source .bashrc" automatically after I edit and save it?

One way, as another answer points out, would be to make a function that replaces your editor call to .bashrc with a two-step process that

  1. opens your editor on .bashrc
  2. sources .bashrc

such as:

vibashrc() { vi $HOME/.bashrc; source $HOME/.bashrc; }

This has some shortcomings:

  • it would require you to remember to type vibashrc every time you wanted the sourcing to happen
  • it would only happen in your current bash window
  • it would attempt to source .bashrc regardless of whether you made any changes to it

Another option would be to hook into bash's PROMPT_COMMAND functionality to source .bashrc in any/all bash shells whenever it sees that the .bashrc file has been updated (and just before the next prompt is displayed).

You would add the following code to your .bashrc file (or extend any existing PROMPT_COMMAND functionality with it):

prompt_command() {
  # initialize the timestamp, if it isn't already
  _bashrc_timestamp=${_bashrc_timestamp:-$(stat -c %Y "$HOME/.bashrc")}
  # if it's been modified, test and load it
  if [[ $(stat -c %Y "$HOME/.bashrc") -gt $_bashrc_timestamp ]]
  then
    # only load it if `-n` succeeds ...
    if $BASH -n "$HOME/.bashrc" >& /dev/null
    then
        source "$HOME/.bashrc"
    else
        printf "Error in $HOME/.bashrc; not sourcing it\n" >&2
    fi
    # ... but update the timestamp regardless
    _bashrc_timestamp=$(stat -c %Y "$HOME/.bashrc")
  fi
}

PROMPT_COMMAND='prompt_command'

Then, the next time you log in, bash will load this function and prompt hook, and each time it is about to display a prompt, it will check to see if $HOME/.bashrc has been updated. If it has, it will run a quick check for syntax errors (the set -n option), and if the file is clean, source it.

It updates the internal timestamp variable regardless of the syntax check, so that it doesn't attempt to load it until the file has been saved/updated again.