bash history-fu

I came across a new blog (seems to have come on-line in March) http://www.epoxyjournal.com. One of the entries was about how to clear command history. Everyone has inadvertently pasted or typed something into the wrong shell. Sometimes its worthwhile to clean up after yourself and sometimes its not. I figured I would offer a suggestion for the times you want to avoid having your embarrassing moments in your ~/.bash_history.

Instead of blowing away your entire current buffer with history -c you can redirect it to another file, flush the buffer to the file, clean it up then append it to your ~/.bash_history. Sure its more work then abandoning your history but insert Godwin’s Law.

So it might look something like this.

$ echo some long one liner you want to preserver
$ echo something embarrassing
$ export HISTFILE=~/tmphistfile
$ history -a
$ grep -v embarrassing ~/tmphistfile >> ~/.bash_history
# re-point your history file to the right one, or just exit the shell

Matt Simmons thought a little oops utility would be nice. So here is my shoot from the hip attempt, haven’t extensively tested it but I think it works.

#!/bin/bash
# wipe your history of lines that match the input
# Usage: oops <embarrassing string>

TEMPHIST=$(mktemp)
export HISTFILE=$TEMPHIST
history -a
grep -v $1 $TEMPHIST >> ~/.bash_history
history -c
rm $TEMPHIST
HISTFILE=~/.bash_history
history -r

2 Comments

  • I’ve always just used this one-liner:

    for i in $(history | grep $PHRASE | awk {‘print $1’} | tac); do history -d $i; done

  • Thats more efficient than writing to a temp file, I didn’t know about the history -d flag. To get slightly more efficient, cut out the extra grep and get. for i in$(history | awk ‘/$PHRASE/ {print $1}’ | tac; do history -d $i;done

    I couldn’t figure out how to execute the bash builtin history command with xargs :)

Leave a Reply

Your email is never shared.Required fields are marked *

To submit your comment, click the image below where it asks you to...
Clickcha - The One-Click Captcha