Sweeten Bash History by Adding Grep

The Problem

While I know about the Ctrl-R key combination in bash to perform an incremental reverse search the history; I often need to grep the history to find what I want. For example, to find out what directory I changed into, I issue the following command:

$ history | grep cd

That’s a lot of typing for a lazy guy like me. Imagine that. I rather spend my time writing this blog that repeating that command.

The Solution

To solve this problem, I created a simple function and placed it in my ~/.bash_profile file:

function h() {
    if [ -z "$1" ]
    then
        history
    else
        history | grep "$@"
    fi
}

Explanation

  • Line 2-5: If the user call the command h without any parameter, the function calls the history command
  • Line 6-7: Otherwise, issue the history command and use grep to search.

Going back to my original example, the command now becomes:

$ h cd

Clearly, this is the way life should be: short and sweet. See you in another post.

3 thoughts on “Sweeten Bash History by Adding Grep

  1. Pingback: Tu propia biblioteca de comandos en Bash « M-x aprende-y-comparte

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