5

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?

10

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.

| improve this answer | |
  • 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 2:30
  • It's even more complicated than that. This appears to be the correct answer: superuser.com/a/734410 – Diagon Sep 18 '18 at 3: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. – Paused until further notice. 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 3: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. – Paused until further notice. Sep 19 '18 at 3:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.