Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# If you, like me, have all of your various source-code-like projects in ~/src/
# this is how to give yourself per-project shell history.
#
# I wish I'd done this years ago.
#
# First, in your .bashrc file, you redefine the cd, pushd and popd builtins to be "do the builtin bit,
# then do one other thing (set_src_history.sh, below) like so:
cd () {
builtin cd "$@"
. set_src_history.sh
export HISTFILE=$NEWHISTFILE
}
pushd () {
builtin pushd "$@"
. set_src_history.sh
export HISTFILE=$NEWHISTFILE
}
popd () {
builtin popd "$@"
. set_src_history.sh
export HISTFILE=$NEWHISTFILE
}
export PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
# That last bit basically kickstarts the history-keeping process and forces immediate logging.
#
# Be advised that this _definitely breaks_ the exclamation-point, run from line M to line N tricks
# if you're using shells in multiple windows. Those numbers and the contents of your history _will not_
# not be in the order you expect; you're racing yourself, and if this ruins something of yours all I
# have for you are repurposed DJ Khaled gifs.
#
# It also won't work if you change directories via export, like "export PWD=/tmp/", but I'm not sure
# how to handle that in an elegant way, and that _seems_ like something that a human user wouldn't do,
# but who knows?
#
# In whatever place you prefer to keep your spare executables (I'm partial to ~/bin/ myself,
# but as long as it's in your path, you do you) put this into the "set_src_history.sh"
# script our modified change-dir files are sourcing.
NAME=`whoami`
PROJDIR=/home/$NAME/src/
if [[ $PWD == $PROJDIR* ]] ; then
NEWHISTFILE=$PROJDIR`echo $PWD | sed s#$PROJDIR#\.#g | sed s#/.*##g`_history
touch $NEWHISTFILE
else
NEWHISTFILE="/home/$NAME/.bash_history"
fi
# Then close your shells and reopen them, so the new contents of .bashrc get picked up.
#
# Now, if you cd into anything under ~/src/project/whatever, you'll have a new bash history
# file called ~/src/.project_history and the history command will refer to it when you're in
# there, and bail you back out to the default ~/.bash_history file when you're out.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment