Bash – How to make Bash flush command history so it can be cleared

bashcommand historylogout

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 run fc -l to see a listing of the most recent commands, then history -d to delete an entry.

$ echo swordfish
swordfish
Oops, that was my password!
$ fc -l -2
1234 ls
1235 echo swordfish
$ history -d 1235
$ fc -l -3
1234 ls
1235 fc -l -2
1236 history -d 1236

If you've already written the history file (for example because you have history -w in PROMPT_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 call history -c. If you want to forget all but the last 3 history entries, set HISTFILE=3 then (on a separate command line) set it back to your usual value.

Related Question