Flush Bash_history After Each Command

If you, like me, often work in a lot of terminals on a lot of servers, or even a lot of terminals on the same one, you may recognise the frustration of a lost bash history. I don’t always gracefully log out of my sessions, so every so often my ~/.bash_history isn’t written and all my flashy commands are lost (the history buffer is only committed when you log out, everything that you see in history is not actually written to disk). I quite often find myself rewriting the same one-liners or long option list just because I closed my konsole or SecureCRT window without first logging out of all the sessions properly.

So I put some effort into finding a solution to this, and whilst reading through the bash manpage, I saw PROMPT_COMMAND. pling

export PROMPT_COMMAND='history -a'

To quote the manpage: “If set, the value is executed as a command prior to issuing each primary prompt.” So every time my command has finished, it appends the unwritten history item to ~/.bash_history before displaying the prompt (only $PS1) again.

So after putting that line in /etc/bashrc I don’t have to find myself reinventing wheels or lose valuable seconds re-typing stuff just because I was lazy with my terminals.

This is one of those things that I should have done ages ago, but never took the time to.

Oct 5th, 2008