Bash – How to get a persistent “history”-file even after a non-clean shutdown

bashcommand historycommand lineshutdown

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?

Best Answer

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.