If I am not mistaken, bash saves its history to ~/.bash_history (or to $HISTFILE) on exit from a login shell session. But - what if you want to occasionally persist it for fear of the shell getting prematurely killed (as in SIGKILL or power failure)? Is this possible without burdening the system or the shell session experience?
Asked
Active
Viewed 1,717 times
4
einpoklum
- 9,515
-
2This is a good read - BashFAQ/088 - How can I avoid losing any history lines? – Inian May 03 '18 at 06:53
-
@Yaron: That question is related, not the same, since I'm not addressing the race condition. Also, it doesn't have a very satisying answer... – einpoklum May 03 '18 at 07:46
-
@einpoklum - the answer describes: How turn history on with every command - won't it answer your needs? – Yaron May 03 '18 at 07:53
-
Read about bash eternal history. – May 03 '18 at 10:54
-
"IIANM" does that mean "If I Am Not Mistaken"? – AJM Dec 14 '23 at 17:36
-
1@AJM: Yes, sorry, expanded that. – einpoklum Dec 14 '23 at 20:45
-
@einpoklum Thanks! – AJM Dec 15 '23 at 12:12
1 Answers
2
By default, Bash saves it's history on exit from shell. Thus it will lose it's current history if it's killed non-gracefully.
You can save your current Bash history by running:
$ history -a
Knowing that, you can make Bash save it's history after each executed command, by running history -a after each executed command. One way to do is via the Bash prompt:
PROMPT_COMMAND='history -a'
This works because the Bash prompt will execute $PS1, $PROMPT_COMMAND, and more, on each new prompt.
Here is a great blog post that got me onto the idea: https://sanctum.geek.nz/arabesque/better-bash-history/
aude
- 292
-
Just a note that the linked URL currently redirects to https://blog.sanctum.geek.nz/better-bash-history/ - but I couldn't update it because of the edit queues. – AJM Dec 14 '23 at 15:36