Ubuntu – How does the history command work

bashbash-historycommand line

When I type any command in the terminal, it doesn't appear in my ~/.bash_history file until I exit my session.

Also, when I manually edit my ~/.bash_history file (for example I remove the last three commands), when I type history it still shows the commands that I removed from the ~/.bash_history file. Only when I exit my session and login again they disappear.

How does my ~/.bash_history file and the history command get synchronized?

Best Answer

When you open a bash terminal it loads the content of ~/.bash_history and builds the active shell's history (in the RAM), adding every command executed in that shell to it – and only to it, not to the file.

Only when you close a bash terminal its history is appended to your ~/.bash_history file.


Options of history:

history -a # save the active shell's history to ~/.bash_history (appending)
history -c # clear the active shell's history
history -d NNN # delete row NNN of the active shell's history
history -r # reload the active shell's history from ~/.bash_history (appending)
history -w # save the active shell's history to ~/.bash_history (overwriting)

Options for ~/.bashrc file

If you want to change this behaviour so that the temporary history is saved to ~/.bash_history directly after executing a command, add this line:

PROMPT_COMMAND="history -a"

If you additionally want every terminal to automatically load the ~/.bash_history file after every command execution, add this line instead:

PROMPT_COMMAND="history -a; history -c; history -r"

If you want to exclude certain commands (e.g. everything beginning with sudo and cat) from being saved, add this line:

HISTIGNORE="sudo*:cat*"