I like saving all my history, but I also find that it easily becomes a mess doing it in one file. So I split it up session, and then I merge it all into one file.
# Eternal bash history.
# ---------------------
HISTCONTROL=
HISTFILESIZE=
HISTIGNORE=
HISTSIZE=
HISTTIMEFORMAT="%Y-%m-%dT%T%t"
# read global history
HISTFILE=~/.bash_eternal_history
history -r
# IIF there's no session history directory, create one
if [ ! -d ~/.bash_history ]; then
[ -f ~/.bash_history ] && mv ~/.bash_history ~/.bash_history.0
mkdir ~/.bash_history
fi
# change history file to one for the session
HISTFILE=~/.bash_history/$$
# If it already exists, take a backup
if [ -f "$HISTFILE" ]; then
mv "$HISTFILE" "$HISTFILE"."$(stat "$HISTFILE" --format='%W')"
fi
# save the current session id + process id
{ export SESSION_ID="$(</proc/$$/sessionid)"; } 2> /dev/null
printf "#$(date '+%s')"'\n# starting session:'$SESSION_ID' process:'$$' in:'"$PWD"'\n' > "$HISTFILE" &&
history -r
# Use trap to save history, not just on logout but also EXIT
trap_exit() {
# Append session history to global history
## Append to local history session to file
cp -f "$HISTFILE" /tmp/history.$$.0
history -a
cp -f "$HISTFILE" /tmp/history.$$.1
## Append local history file to global history
printf "#$(date '+%s')"'\n# ending session:'$SESSION_ID' process:'$$' in:'"$PWD"'\n' |
cat "$HISTFILE" - >> ~/.bash_eternal_history
}
trap trap_exit EXIT