A Quick and Dirty Recursive Grep Alias

Posted on December 06, 2014 in bash, grep, cli

Oh wow, it's been awhile since the last update so here's a quick bash script I've hacked together to save me countless seconds when using grep on the command-line. Maybe they'll be of use to someone, maybe not.

The Alias

recursiveGrep() {
  grep -sorn --include \*.php --include \*.html --include \*.js "$@" . --exclude-dir=.git --exclude-dir=.idea
recursiveGrepInsensitive() {
  grep -soirn --include \*.php --include \*.html --include \*.js "$@" . --exclude-dir=.git --exclude-dir=.idea
alias rg=recursiveGrep
alias rgi=recursiveGrepInsensitive

To search recursively all I need to do is type something like rg findthisstring or rgi findThisString (for case-insensitive searching.)

But what does it all mean, Basil?

It's simple. Dealing with primarily PHP, HTML, and JavaScript I simply ignore all other file types by defining:

--include \*.php --include \*.html --include \*.js

You could easily modify this to include \*.css, or \*.rb.

I also allow unlimited parameters to be included in my grep by passing through "$@". If you're paying attention, note that I've included quotes around the $@. This allows me to search things like rg "I really need to find this string". Without the quotes, the script wouldn't return the results I'm actually looking for.

Other noteable parameters are -s which ignores errors that grep occassionaly tosses.


Thomas Lackemann :)


Tom is the founder of Astral TableTop. He's a homebrewer, hiker, and has an about page. Follow @tlackemann on Twitter for more discussions like this.