How does the history command work?

Solution 1:

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*"