While there are working answers below, I still wonder why it doesn't work with history -d X. I came across this question because I had just done history | grep search_str | sort -nr | awk '{print $1}' | while read i; do history -d $i; done. No error, but nothing deleted. Anybody can explain why?
–
mivkJun 4 '13 at 17:47

4 Answers
4

The history command just operates on your history file, $HISTFILE (typically ~/.history or ~/.bash_history). It'll be much easier if you just remove the lines from that file, which can be done many ways. grep is one way, but you have to be careful not to overwrite the file while still reading it:

Careful... histfile is unpredictable, if you have many open shells, it's no telling what exactly will get saved and in what order. Can anyone confirm that already open shells will not rewrite the history they loaded at initialization, when closed?
–
orionJan 13 at 17:02

Michael Mrozek's answer will work if you don't care about removing commands from the current session. If you do, you should write to the history file before doing the operations in his post by doing history -a.

Also, after you have removed the entries that you want from your history file, you can reload it by issuing history -c, then history -r.

So, if you wanted to eg. delete multiple lines with a password in it, simply replace "SEARCH_STRING_GOES_HERE" with the password.
This will search your entire history for that search string and delete it.

2 things to be aware of

grep uses regex unless you supply -F as an argument

The command will show 1 error, once there are no more matches. Ignore it.