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.
alias
January 3, 2011
you just need to add following line in $HOME/.bashrc
alias hisgrep=’history | grep’
Hai
January 3, 2011
@alias that works, too. However, you cannot type hisgrep without arguments.