How to get a persistent "history"-file even after a non-clean shutdown?

5,089

You should always use shutdown.

You can add this to your ~/.bashrc file:

PROMPT_COMMAND='history -a'

This will append the in-memory history to your history file after each command is completed.

Share:
5,089

Related videos on Youtube

Jonas
Author by

Jonas

I'm a computer science student.

Updated on September 17, 2022

Comments

  • Jonas
    Jonas over 1 year

    I am trying Ubuntu Server 10.10 in VirtualBox. I like that the commands I run is saved in a "history"-file that can be shown with the history command. But if I just turn off VirtualBox without the shutdown command, then next time when I boot, the commands from the last session is not saved in the history file.

    The commands are only saved if I shutdown the machine with the shutdown command. E.g. shutdown -P 0.

    Is there any way I can save the history file after every command so they are persistent even after a "non-clean" shutdown?

  • Diagon
    Diagon over 5 years
    Don't you need history -n also? That way anything appended to the history file by this terminal is read in by the other terminal?
  • Diagon
    Diagon over 5 years
    It's even more complicated than that. This appears to be the correct answer: superuser.com/a/734410
  • Brian Rasmussen
    Brian Rasmussen over 5 years
    @Diagon: That looks like it results in a better quality history file, but it could add significant overhead since it reads the history file for every prompt if you keep a large one as I do.
  • Diagon
    Diagon over 5 years
    Yes, I see that. I also keep a large one. The issues involved do not appear simple. For you or anyone else who might be interested, there has been extensive discussion on these issues, both here and here. Since I would not only like a combined history, but also have some record of what I did, particularly in case I screw up, I'm considering this.
  • Brian Rasmussen
    Brian Rasmussen over 5 years
    @Diagon: I use a form of my answer here and save the entries in a file separate from .bash_history. I have it record the directory that I'm in when I execute the command along with other information in addition to the command line.
  • Diagon
    Diagon over 5 years
    That looks fantastic. You've even got a switch for the tty! I'll probably have a question or two, but I'll ask over there. Maybe you want to consider putting it on github (or some non-MS version thereof)?