Linux – bash save history without exit

bashcommand historylinux terminalUbuntu

in linux ubuntu bash terminal. is there any way to save bash history without writing exit?
i've set the config to
"HISTCONTROL=erasedups"

which in my opinion works better than ignoredups.

anyways for some reason it wont save the last few commands in the bash terminal unless i type in "exit". I'm used to just click the cross on the terminal window, so i'm always annoyed that the last commands were not saved when i relogin.

reminder:
http://www.thegeekstuff.com/2008/08/15-examples-to-master-linux-command-line-history/#more-130

Best Answer

Bash History

Any new commands that have been issued in the active terminal can be appended to the .bash_history file with the following command:

history -a

The only tricky concept to understand is that each terminal has its own bash history list (loaded from the .bash_history file when you open the terminal)

If you want to pull any new history that's been written by other terminals during the lifetime of this active terminal, you can append the contents of the .bash_history file to the active bash history list

history -c;history -r

This will clear the current history list so we don't get a repeated list, and append the history file to the (now empty) list.

Solution

You can use the bash variable PROMPT_COMMAND to issue a command with each new prompt (every time you press enter in the terminal)

export PROMPT_COMMAND='history -a'

This will record each command to the history file as it is issued.

Result

Now any new terminal you open will have the history of other terminals without having to exit those other terminals. This is my preferred workflow.

More Precision

Let's say (for some reason) you have two terminals that you're using simultaneously and you want the history to reflect between both for each new command.

export PROMPT_COMMAND='history -a;history -c;history -r'

The main drawback here is that you may need to press enter to re-run the PROMPT_COMMAND in order to get the latest history from the opposite terminal.

You can see why this more precise option is probably overkill, but it works for that use case.

Related Question