Open-Source Software Shortcut, Excluding Directories From Grep

by Juliet Kemp

Tip of the Trade: Want to use Grep without including some directories? Here's a simple, yet efficient way, for the open-source software to find what you're looking for.

I work on a project on which I regularly want to grep the directory tree for a particular word but without including the cvs/ and doc/ directories. Happily, grep has an exclude-dir option to do just this:

grep -R --exclude-dir=cvs --exclude-dir=doc foo *
It searches recursively for foo without looking in cvs/ or doc/, so the output isn't clogged up with unwanted results. Great.

The problem with this is that (in true sys admin style) I'm lazy and don't want to do all that typing. One solution to this is to set up an alias in the ~/.bashrc file:

alias mygrep="grep -R --exclude-dir=cvs --exclude-dir=doc"

Type source ~/.bashrc, once you've edited the file, to set this up in your existing session. Then

mygrep foo *
produces the required result.

However, that still leaves that extraneous * at the end of the command -- it's easy to forget to type it, in which case grep will hang. An even better solution, then, is to set up a bash function (again, in the ~/.bashrc file), which will take a single argument (the value to search for) and then run grep on it:

function mygrep ()
    grep -R --exclude-dir=cvs --exclude-dir=doc ${1} *
Source the ~/.bashrc file again, and try mygrep foo.

One final refinement is to check for the search value before you run the search:

function mygrep () {
	if [ ${1} ]; then 
		grep -R --exclude-dir=cvs --exclude-dir=doc ${1} *;

Bash functions are a powerful way to do things that are beyond the scope of a simple alias. They are handy for saving time on regularly used commands like this.

Juliet Kemp has been messing around with Linux systems, for financial reward and otherwise, for about a decade. She is also the author of "Linux System Administration Recipes: A Problem-Solution Approach" (Apress, 2009).

Follow ServerWatch on Twitter

This article was originally published on Monday Mar 29th 2010
Mobile Site | Full Site