7

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?

  • 2
    it's in RAM... Where is bash's history stored? – Zanna Sep 6 '17 at 16:11
  • "When I type any command in the terminal" Not actually true. When you put a space in front of the command by default it does not save that command. – Rinzwind Sep 7 '17 at 6:55
  • @Rinzwind the behavior of saving the command even if it has a space in front can be changed by editing the value of your HISTCONTROL environment variable. – sys0dm1n Sep 7 '17 at 7:14
  • @sys0dm1n "by default" – Rinzwind Sep 7 '17 at 7:49
9

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

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.