dandavis.dev


The Bash History I Always Wanted

Using many terminal windows and toolbox containers leads to a trashed ~/.bash_history. If I want to quickly pull up a command I ran in another terminal with Ctrl+r, the command won't be there. This is because by default, the history file is not written until you exit the current shell.

In my opinion, commands should be written to the history file in the same order they were entered. After explaining my problem to gpt-5.4-mini we came up with a solution:

# Put this snippet in ~/.bashrc
export HISTSIZE=1000000
export HISTFILESIZE=1000000
export HISTCONTROL=ignoreboth
shopt -s histappend

__history_sync() {
  builtin history -a
  builtin history -n
}

case ";$PROMPT_COMMAND;" in
  *";__history_sync;"*) ;;
  *)
    if [[ -n "$PROMPT_COMMAND" ]]; then
      PROMPT_COMMAND="__history_sync; $PROMPT_COMMAND"
    else
      PROMPT_COMMAND="__history_sync"
    fi
    ;;
esac

If you are extra paranoid like me you can also make ~/.bash_history append-only.

sudo chattr +a ~/.bash_history

References