I accidentally put a password on the command line and needed to clear Bash shell history. That was easy enough with echo "" > ~/.bash_history
.
I added the same to my .bash_logout
just in case for the future. However, when I check history after a logout/logon, the last command I entered is still present in the history file. More correctly, two commands are present: the last command I entered, and the exit
command from the logout.
How do I make Bash flush the command history to file so that I can clear it upon logout?
Best Answer
Bash doesn't write its history to the history file until it exits or you explicitly invoke
history -w
. So if you just added your password in the current shell's history, it hasn't been written to.bash_history
yet, it's just sitting there in memory. You can runfc -l
to see a listing of the most recent commands, thenhistory -d
to delete an entry.If you've already written the history file (for example because you have
history -w
inPROMPT_COMMAND
or a debug trap), then do this and edit.bash_history
as well.If you want to forget the current shell's history altogether, unset
HISTFILE
and make sure it stays unset until the shell exits. If you want to forget the current history up to this point but start recording, you can callhistory -c
. If you want to forget all but the last 3 history entries, setHISTFILE=3
then (on a separate command line) set it back to your usual value.