Bash – How to protect against purge of bash history

bashcommand historyi3shutdown

Following the answer:

When closing multiple bash instances at the same time, there is a
known race condition that may cause the history to be cleared. This
occurs because there is no locking used when the bash history file is
written.

How can I prevent against this cause of bash history purge?

I use i3wm and I think that it happens mostly when I shutdown the computer before I manually close urxvt terminals. The command used (via keybind) for shutdown is systemctl poweroff.

Best Answer

The source of the race condition is because bash only writes the history file as the shell exits. Plus it will over write the existing history file if multiple shells are running, only the last to exit will dominate the history.

So one solution is to write history out, after EVERY command. There or some negative consequences to this, such as you'll be able to up arrow history events occurring in other windows, and therefor will expose to all open shells (that you own) what commands you just ran. The most likely place this will bite you is if you are doing a repetitive set of commands, like 'up arrow N times, then hit enter' over and over again. If in a closed window a background process ends, then suddenly you'll need to pay closer attention what command is really 'up arrow N+1 times' risking running the wrong command.

To turn 'history on with every command' try adding these to you .bashrc (number of lines of history to store are just examples, you can change them for your comfort)

HISTFILESIZE=400000000
HISTSIZE=10000
PROMPT_COMMAND="history -a"
export HISTSIZE PROMPT_COMMAND

shopt -s histappend
Related Question