Last Updated: February 25, 2016
·
429
· parvizp

Git-repo-based Shell History

I typically have many projects that I'm working on and they are each in their own Git repo. Looking at the shell history for a project is one way to get a quick reminder of what I last was doing. I wanted a way to isolate the history within a given Git repo. In other words, if I execute a command in any directory under a Git repo, I want that command to belong to a history file for that Git repo.

This script for more general directory-based history can be modified as follows:

### Git-repo-directory-based history
function custom_cd()
{
    builtin cd "$@" # do actual cd

    # If this directory is in a Git repo, use the root directory for history file.
    HISTORY_PATH=$(git rev-parse --show-toplevel 2> /dev/null) && export HISTFILE=$HISTORY_PATH/.bash_history || export HISTFILE="$HOME/.bash_history"
}
alias cd="custom_cd"
export HISTFILE="$HOME/.bash_history"

export HISTTIMEFORMAT="%h/%d - %H:%M:%S "
export HISTCONTROL=ignoredups:erasedups
export HISTSIZE=1000000
export HISTFILESIZE=1000000
shopt -s histappend ## append, no clearouts
shopt -s histverify ## edit a recalled history line before executing
shopt -s histreedit ## reedit a history substitution line if it failed

## Save the history after each command finishes
## (and keep any existing PROMPT_COMMAND settings)
export PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"