I did some tests about history:
I ran
history-c
and then logged out. This cleared history for the current shell.I ran
history -c && history -w
. This deleted everything.I deleted the entire contents of the history file by vi editor:
$vi ~/.bash_history
. And then I logged out. In the next login, when I ranhistory
only the lines or commands of last shell session is there.
This shows that there are differences between history -w
and the action when we close a shell session.
What really happens when we close a shell session?
I think history -w
overwrites memory contents to history file, and history -c
deletes memory contents. Is this correct?
When dealing with Bash history, we have two kinds:
.bash_history
file on diskWhen Bash starts (assuming a default configuration), it will load the contents of your
.bash_history
file into the history list in memory (after truncating it to the configured size, if necessary).Then you type your commands which get appended to the history list in memory only. The history file on your disk does not get touched.
Exiting your Bash session regularly (not forcefully killing it or causing it to crash somehow) by default truncates your history list in memory to fit the configured maximum size and then appends only new entries from the current Bash session (because by default the
histappend
option is enabled) to your history file on the disk, without deleting removed entries or re-adding content from previous sessions.When you run
history -c
you clear the complete history list in memory, but again this does not affect the history file on the disk.Running
history -w
writes your current history list in memory to the history file on disk. It does not append new entries but overwrites the complete file. Therefore runninghistory -c && history -w
effectively clears the history file as well.Manually clearing your history file by editing it from within a running Bash session has not the expected effect or permanently deleting the entire history so far, because the history list in memory which still contains all old entries from the history file will stay intact.
On exiting your Bash session, the history file will get rewritten with the data from the history list. However, as by default the
histappend
option is enabled, only new entries from the current Bash session will be written to the file, older history data gets discarded. You would have to runhistory -w
to save the full history list to disk.What exactly happens when a Bash shell starts and exits can be read in
man bash
: