Lyte's Blog

Bad code, bad humour and bad hair.

Archiving Bash History

This is a short one, but someone may find it useful.

Normally when you log out of bash it will write the history to ~/.bash_history. This is all well and good until you have multiple terminals open, because the last terminal to close will overwrite whatever is in ~/.bash_history.

I’ve written a little bit of bash code that I now put in my ~/.bash_logout file to take whatever is in the history buffer at logout and store it in a file something like ~/.bash_history_archive/2009/04/23/210400_12345.

1
2
3
4
5
6
7
8
9
10
11
PID=$$
# DATE as YYYY/MM/DD
DATE=`date +%Y/%m/%d`
# TIME as HHMMSS in 24 hour time
TIME=`date +%H%M%S`
HIST_DIR=$HOME/.bash_history_archives/$DATE
HIST_FILE=$HIST_DIR/${TIME}_${PID}
# create $HIST_DIR if it doesn't exist
[[ -d $HIST_DIR ]] || mkdir -p $HIST_DIR
# 'history -w' writes the current contents of history to a file
history -w $HIST_FILE

Well that’s it.

Comments