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
  • 4
  • 19
  • 22

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.

Dennis Williamson
  • 6,620
  • 1
  • 34
  • 38
  • 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](https://unix.stackexchange.com/a/18443) and [here](https://stackoverflow.com/questions/338285/prevent-duplicates-from-being-saved-in-bash-history#). 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](http://nodsw.com/blog/leeland/2012/03/07-all-bash-history-revisited-load-time-solved-plus-directory-history). – Diagon Sep 19 '18 at 03:23
  • @Diagon: I use a form of [my answer here](https://stackoverflow.com/a/960684/26428) 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