Skip to content

Instantly share code, notes, and snippets.

@mhoye
Last active January 2, 2024 21:50
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhoye/469ed97d7887b451da5d45b87acb53f5 to your computer and use it in GitHub Desktop.
Save mhoye/469ed97d7887b451da5d45b87acb53f5 to your computer and use it in GitHub Desktop.
# 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.
#!/bin/bash
# ^^ it has to be bash because there's a subtly hidden bashism in line 55.
# If you want to use zsh or some other shell, now you have a fun puzzle!
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