Tuesday, September 13, 2011

Sync bash history between sessions on the fly

If you work with more then one bash terminal at a time, it can be annoying that the bash history is only available in the other session after you closed the terminal (default bash behavior).

You can fix it by adding this to your .bashrc

shopt -s histappend
export PROMPT_COMMAND="history -n; history -a"
More about it here: http://briancarper.net/blog/248/

*EDIT:
I found it confusing that the history is always synced, even in the current session. This can be confusing while working, so i changed the above a bit:

HISTSIZE=10000
HISTCONTROL=ignoreboth:ignoredups:erasedups
shopt -s cmdhist
shopt -s cdspell
shopt -s histappend
#PROMPT_COMMAND="history -n; history -a"
PROMPT_COMMAND="history -a"
Beside the obvious changes  there are some more variables changes . "HISTCONTROL=ignoreboth:ignoredups:erasedups" to prevents bash to add dups. So your .bash_history keeps clean. Beside that i have added some more fun stuff. "cdspell" fixes typos while changing directories (yeah) and HISTSIZE increases the history size to 10000 lines. 


Removing "history -n;" has the effect, that the history is still up to date when you open a new terminal but existing terminals will not get the changes immediately. You have to execute "history -n" manually if you need the changes in the current terminal.