6

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?

Jonas
  • 1,593

1 Answers1

13

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.

  • 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 Sep 18 '18 at 02:30
  • It's even more complicated than that. This appears to be the correct answer: https://superuser.com/a/734410 – Diagon Sep 18 '18 at 03:00
  • @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. – Dennis Williamson Sep 18 '18 at 15:44
  • 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. – Diagon Sep 19 '18 at 03:23
  • @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. – Dennis Williamson Sep 19 '18 at 03:51
  • 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)? – Diagon Sep 19 '18 at 05:53