Bash – Archive history without exiting the shell

bashcommand historyzsh

I just realised that a workflow I've been using for years, doesn't do what it is supposed to do. Since I haven't realised that for such a long time, you might think it's not worth putting much effort into it, but it turns out that right now, it has become somewhat important.

What am I talking about? Okay, I have tmux running with several sessions and each session has different windows and so on. Working like that is wonderful. There's one downside to it, though. When the server gets restarted, for whatever resason, it closes all my sessions. Fair enough, cannot be avoided and doesn't happen often. However, the annoying part is, that all my zsh or bash history is gone as well. This is a problem. I rely on my history, maybe far too much.

I was circumventing this problem by hitting fc -W (in zsh) every now and then. I thought this would append history that is in the memory and I would then only lose the part between my last invocation of fc -W and the restart of the server. But that's not what it does. If I use fc -W in one window, then fc -W in another one, the history from the first window would be overwritten by the history from the second window. I would need to use fc -R first, but this would duplicate the whole history… basically I was misusing the fc command the whole time.

Here's the question: How can I make sure to not lose any of my history when I'm in tmux and there is a sudden power cut? Note:

  • I use infinite history, in case that matters.
  • Losing some of the history is ok, i.e. if I have to invoke a command by hand (or in a cronjob) and I lose the part of the history since the command has last been run, that's fine.
  • Exiting the terminal and open up new one is not the solution.
  • I don't want to store my commands directly to the history, since this mixes up different histories.
  • Solutions for both bash and zsh are welcome. zsh is preferred.

Edit: Highlight the part that everyone seems to misunderstand.

Best Answer

In zsh, use fc -AI to save your history, not fc -W. Use -A, not -W, otherwise the history from other shell instances is overwritten. And -I saves only the new history entries since the last save.

Given your workflow, rather than saving manually, you should probably save the history automatically. Turn on the inc_append_history option to save each command to the history file immediately before it gets executed.

While it's possible to achieve the same effect in bash, properly sharing history between bash instances is harder. See Preserve bash history in multiple terminal windows

Related Question