From: rouble on
Hi All,

I was trying to get multiple bash sessions to share a common history.
It seems the standard way of doing this is by configuring the
following:

export PROMPT_COMMAND='history -a; history -n'

However this seems to be broken. There is an email on gnu.bash.bug
detailing the bug:
http://groups.google.com/group/gnu.bash.bug/browse_thread/thread/873e3e06f76c78c7/5d5d5e99945bcd69?q=history&rnum=4#5d5d5e99945bcd69

I then tried to use a combination of:
history -a; history -r

to achieve the same thing. However 'history -r' kept reading and
appending the entire history to the current sessions history. To
correct this, I tried:
history -a; history -c; history -r.

The logic being that after the command was appended to the HISTFILE, I
would clear the current sessions history and reload the entire history
from HISTFILE. This seems to work great - except if I have a completely
empty HISTFILE to begin with - in which case, HISTFILE never gets
updated. Am I missing something or is this just another bash bug ?

My bash code is attached below. Let me know if there are anything
obviously wrong with it.

shopt -s histappend
shopt -s cmdhist
export HISTFILE_ARCHIVE=.bash_history.archive
export HISTTIMEFORMAT="%D - %H:%M:%S "
export PROMPT_COMMAND=archive_history
archive_history () {
TIME_BEFORE=`stat --format=%Y ${HISTFILE}`
history -a
history -c
history -r
TIME_AFTER=`stat --format=%Y ${HISTFILE}`
if [ $TIME_AFTER -gt $TIME_BEFORE ]; then
cat ${HISTFILE} | tail -2 >> ${HISTFILE_ARCHIVE}
fi
}

Note that the script above also archives every command, but that is
beyond the scope of this question.

Oh and yes, I do know about zsh and the magical share_history :-)

TIA,
rouble