Last Updated: May 02, 2019
·
959
· stelcheck

Bash profile auto-reload

Got tired of having to source my bash profile every time I did a small change like changing environment variables and so on. That gets annoying when you have 5 tabs+ with split windows in iTerm/Terminator/etc.

I was about to write a small 3-liner here that would define a reload function in your profile, when I realised - why not have the shell pick up changes and reload the profile for you instead?

#
# Quick helper function to reload the profile
#
reload () {
    source ~/.bash_profile
}

checkProfile () {
    #
    # Set the hash command - this should work only on OS X
    #
    HASH_CMD="md5 -q"

    #
    # Generate a quick hash
    #
    CURRENT_HASH="`${HASH_CMD} ~/.bash_profile`"

    #
    # If there is a hash difference, set
    # BASHPROFILE_HASH to the current hash value.
    # If BASHPROFILE_HASH's current value is not empty,
    # reload the bash profile
    #
    if
        [ "${BASHPROFILE_HASH}" != "${CURRENT_HASH}" ]
    then
        OLD_HASH="${BASHPROFILE_HASH}"
        export BASHPROFILE_HASH="${CURRENT_HASH}"

        if
            [ "${OLD_HASH}" == "" ]
        then
            return
        fi

        export BASHPROFILE_HASH="${CURRENT_HASH}"
        echo "~/.bash_profile has been modified, reloading..."
        reload
        return
    fi
}

#
# Prompt command defines a command that
# will run after every command execution, before echo'ing PS1.
# 
PROMPT_COMMAND="checkProfile"

Obviously, this is not perfect (what if the profile sources other scripts?), but for those cases, just manually reload by using reload.

Or suggest a bullet-proof way to parse a source tree for changes in bash not involving file watching :)