Reputation: 1972
The .bash_history
file is a life-save for many of us. Unfortunately, BASH only seems to save the commands of a session when that session is closed (via exit
).
It's a tragedy, then, when all your commands from an important session are vaporized when a session is closed unexpectedly -- before it gets to archive all the commands with fancy syntax that took hours to get right....
This happens to me when I forget to close a SSH connection when leaving work, and it gets disconnected due to inactivity (Write failed: broken pipe
), or when I restart my computer without closing my terminals manually, and so on.
I would love to have my BASH commands archived after some interval -- say every 10 minutes -- so that if I do close a session, my commands will still be there. This seems like something a lot of people might find useful.
Does anyone have an idea of how to do this?
Ideally....
~/.bashrc
bash
, or other "hacks"StackOverflow-ers -- consider yourself challenged!
Upvotes: 8
Views: 3633
Reputation: 1328
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
Upvotes: 4
Reputation:
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_COMMAND
If set, the value is executed as a command prior to issuing each primary prompt.
So just put this into .bashrc
PROMPT_COMMAND="history -a"
Upvotes: 13