I accidentally typed password into bash command line

You can remove just the offending line from bash's history, instead of clearing the entire history. Simply remove the line with the -d flag, then save (write) the new history with the -w flag:

$ history
351 ssh [email protected]
352 my_password
$ history -d 352
$ history -w

There are two parts to this:

  • bash stores the history in a file ~/.bash_history which is, by default, written to at the end of the session
  • the history that is kept in memory

To be safe, you need to clear it from the session:

history -c

and truncate the history file as needed:

> ~/.bash_history

If your session in which you typed the password is still open, then another way to cover your trace is to set the HISTFILE variable to the null device so that the history would not be written to ~/.bash_history when the session exits:

export HISTFILE=/dev/null

Since bash (at least all historic and current versions I'm aware of) does not automatically save history until you exit, a generally applicable strategy when you have typed a command that you want to ensure never gets saved is to immediately type:

kill -9 $$

This kills the shell with SIGKILL, which can't be caught, so the shell has no way to save anything on exit.

Most other approaches involve scrubbing after the fact (i.e. after the data has already hit the disk), which has a lot more chance for error (missing a copy), especially if the system might be using btrfs or similar.