Search code examples
linuxbashgitdotfiles

How to write git commands to separate history file?


I'd like to stop git commands from writing to $HISTFILE and instead track them in their own file.

I expect all non-git commands to be written to $HISTFILE and all commands matching "git*" written to ~/.git_history.


Solution

  • Add the following function to your .bashrc (or .bash_login if you are using a Mac) and restart the terminal.

    git() {
       fc -nl -0 | cut -c3- >> ~/.git_history
       history -d -1
       command git "$@"
    }
    

    When you use git in your shell this function will be called instead.

    • The first line extracts your git command exactly how it would be stored to .bash_history (this includes unexpanded variables, quotes and so on) and appends it to ~/.git_history.
    • The second line deletes your git command from bash's regular history.
    • The last line executes your git command as usual.

    As discussed in the in the comments, .git_history will only serve as a log of entered git commands. You cannot use or ctrlR to get an entered git command back – not even in the same session.