Monday, 5 July 2010

BASH: Per directory BASH history

A while ago I found this post, describing how to have a per directory bash history. I have been meaning to implement this for a while and today managed to.

It enables each directory to have a separate searchable bash history file. So simply by changing into a directory you can view what you did in there. I think this will be useful backup for remembering what commands I used and for editing to make scripts etc.

I have also added an hgrep command, to search all of the history files as I can imagine I will forget which directory I was in when I did something I want to do again. I have not decided wether this grep function should return the directory where the command was run or not. I will see after using it for a while.

If you would like to implement this, add the following code to your .bashrc file

hgrep (){ find ~/.dir_bash_history/ -type f|xargs grep -h $*;}

# Usage: mycd
# Replacement for builtin 'cd', wh ich keeps a separate bash-history
# for every directory.
shopt -s histappend
alias cd="mycd"
export HISTFILE="$HOME/.dir_bash_history$PWD/bash_history.txt"

function mycd()
history -w # write current history file
builtin cd "$@" # do actual c d
local HISTDIR="$HOME/.dir_bash_history$PWD" # use& nbsp;nested folders for history
if [ ! -d "$HISTDIR" ]; then # create folder if neede d
mkdir -p "$HISTDIR"
export HISTFILE="$HISTDIR/bash_history.txt" # set& nbsp;new history file
history -c # clear memory
history -r #read from current histfile

The top line is my hgrep function, remove the -h if you want to see which directory each of the returned history items was run in. The rest should be transparent, just cd as normal and a new history file will be created.


  1. what about:

    export PROMPT_COMMAND="export HISTFILE=$(pwd)/.bash_history"

    or something like that

  2. When writing articles, one must deal with the terms of service (TOS) of article directories. This article touches briefly on this subject as a lot of article writers seem to have a problem with it. Online Marketing