Bash alias-function for deleting all items from history that match a search

Add this to your ~/.bashrc file and then load it with either . ~/.bashrc or source ~/.bashrc.

:<<COMMENT
   Deletes all lines from the history that match a search string, with a
   prompt. The history file is then reloaded into memory.

   Examples
      hxf "rm -rf"
      hxf ^source

   See:
   - http://unix.stackexchange.com/questions/57924/how-to-delete-commands-in-history-matching-a-given-string
COMMENT
#The unalias prevents odd errors when calling". ~/.bashrc" (May result in
#"not found" errors. That's okay).
unalias hxf
hxf()  {
   read -r -p "About to delete all items from history that match \"$1\". Are you sure? [y/N] " response
   response=${response,,}    # tolower
   if [[ $response =~ ^(yes|y)$ ]]
   then
      #Delete all matched items from the file, and duplicate it to a temp
      #location.
      echo -e "grep -v \"$1\" \"$HISTFILE\" > /tmp/history"
      grep -v "$1" "$HISTFILE" > /tmp/history

      #Clear all items in the current sessions history (in memory). This
      #empties out $HISTFILE.
      echo "history -c"
      history -c

      #Overwrite the actual history file with the temp one.
      echo -e "mv /tmp/history \"$HISTFILE\""
      mv /tmp/history "$HISTFILE"

      #Now reload it.
      echo -e "history -r \"$HISTFILE\""
      history -r "$HISTFILE"     #Alternative: exec bash
   else
      echo "Cancelled."
   fi
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s