Flush commands to bash history immediately 19 Jan 2012
On my everyday work, I use to have "zounds" of open terminals in every possible manner! I run different commands in every terminal and I forgot lots of them open for a long time. Frequently, I have to run "old" commands. The way I am doing this in most of the cases is by reverse searching in the history, retrieving and running the command by using CTRL-R. But as I am leaving my workstation open for hours or even days (not to say months :p), there is a high probability that my useful commands were run in a terminal that was never closed or terminated properly. So all pending history was never appended or flushed (including the one I would like to rerun) to the bash history file. Moreover, often there are cases e.g. when someone is working with his laptop while an immediate non-graceful shutdown may cause even the loss of parts of the command history.
A quick solution that I found to solve this problem, is summarized in the following code snippet:
export PROMPT_COMMAND='history -a'
Just include the above code to your .bashrc file and reload it with ". ~/.bashrc" or "source ~/.bashrc". This will create a bash environment variable carrying a command. "The value is executed as a command prior to issuing each primary prompt" as bash man page states. Yet another command to your bloated environment, but I think the pros are more than the cos in this case.
Thats it! If you want to test it just jump to a new terminal and run:
$ tail -f ~/.bash_history
From now on you'll not lose any of the precious commands you write.