BASH: Is there a way to automatically save recent lines to my bash history during a period of inactivity? BASH: Is there a way to automatically save recent lines to my bash history during a period of inactivity? shell shell

BASH: Is there a way to automatically save recent lines to my bash history during a period of inactivity?


You can use history command with -a option:

history-a     Append the ``new'' history lines  (history  lines  entered  since  the       beginning of the current bash session) to the history file.

You can write each and every command to history file at once with a little help of PROMPT_COMMAND function:

PROMPT_COMMANDIf set, the value is executed as a command  prior  to  issuing  each  primary prompt.

So just put this into .bashrc

PROMPT_COMMAND="history -a"


According to this bash will (usually) receive a SIGHUP on disconnect.

Using trap we can write the history (lame as #*?! that bash doesn't do it by default though..):

function rescue_history {    history -a}trap rescue_history SIGHUP

Put the above in your .bashrc