All things Sysadmin
Just another manic Monday

Flush bash_history after each command

October 5th, 2008 by admin

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.

Posted in Sundry sysadmin

4 Responses

  1. Nikesh

    Excellent tip

  2. Treviño

    Finally… I was figuring how to get that since long time…

    Many thanks! I had the same problem too :P

  3. Treviño

    I was thinking that this way is very useful if you use only one shell, but if you open more than one shell and you’d like they to use the same history it would be more useful something like
    export PROMPT_COMMAND=’history -a; history -r’

    So the file history will be updated on each command, and all the shells will be synced to the latest history content.

    This works well with my konsole ;)

  4. Erik Ljungstrom

    Yes, that would have that effect. It’s a matter of taste, I think it would mess too much with my head to have the history from other terminals in my current one, especially since if what I did in all of them were pertinent to the same thing, I’d do it in only one in the first place.
    But yes, if that suits your purposes, it’ll work just fine!

    Cheers,
    Erik

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.