Is it possible to make writing to .bash_history immediate?
A simple solution as detailed in Update Bash History in Realtime.
It says to put those commands in the .bashrc config:
shopt -s histappend
PROMPT_COMMAND="history -a;$PROMPT_COMMAND"
The first command changes the .history
file mode to append. And the second configures the history -a
command to be run at each shell prompt. The -a
immediately writes the current/new lines to the history file.
Related for zsh:
- How do you share history between terminals in zsh?
Try putting this into your .bashrc
:
shopt -s histappend # append to history, don't overwrite it
export PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
Credit here: https://stackoverflow.com/questions/103944/real-time-history-export-amongst-bash-terminal-windows/3055135
history -c
clears the history of the running session. This will reduce the history counter by the amount of $HISTSIZE
. history -r
read the contents of $HISTFILE
and insert them in to the current running session history. This will raise the history counter by the amount of lines in $HISTFILE
.
I think it means that the commands are available almost immediately (you have one terminal, write echo 1
, second terminal echo 2
, first echo 3
and upon pressing down arrow twice, you should have echo 2
available. You must issue a command in a given terminal to have access to what has been written.
I have a large history file with about 100000 entries, and the variants that clear the history list and read the whole history file (using history -c
and history -r
) introduce a noticeable (maybe 0.2 second) delay before the prompt is displayed. Using history -n
so that only new lines are read from the history file is faster:
shopt -s histappend
PROMPT_COMMAND='history -a;history -n'
PROMPT_COMMAND
does not have to be exported because it is a shell variable.