Bash history finally done right

By default bash history is bad at sharing between terminals. I want:

  • Union of all terminals’ history in a new terminal
  • Each terminal to keep its own history while it is open
  • (optional) Type “sudo apt” and then press “up arrow” and it will search for everything starting with “sudo apt”
  • (optional) A file that keeps all of my history forever

And finally, via this post and the comment by Jo Liss, I’m happy:

# Insert into .bashrc

# Make sure you remove the existing history lines
# Usually:
###
#    HISTCONTROL=ignoreboth
#    shopt -s histappend
#    HISTSIZE=1000
#    HISTFILESIZE=2000
###

HISTSIZE=9000
HISTFILESIZE=$HISTSIZE
HISTCONTROL=ignorespace:ignoredups
_bash_history_sync() {
    builtin history -a
    HISTFILESIZE=$HISTSIZE
}
history() {
    _bash_history_sync
    builtin history "$@"
}
PROMPT_COMMAND=_bash_history_sync

if [[ "$-" =~ "i" ]] # Don't do this on non-interactive shells
then
    # Add MATLAB-style up-arrow, so if you type "ca[UP ARROW]" you'll get
    # completions for only things that start with "ca" like "cat abc.txt"
    bind '"\e[A":history-search-backward'
    bind '"\e[B":history-search-forward'
fi

# OPTIONAL: Keep a second history file forever
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ; }"'echo $$ $USER \
           "$(history 1)" >> ~/.bash_eternal_history'

09/4/18