Chris
Chris

Reputation: 13

Grep in bash script giving no results

I wanted to make a little script to save me some typing, but unfortunately I get no output:

#!/bin/bash
grep  -Hnr \"$1\" --include \"*cpp\" --include \"*h\" $2

I played quite a lot with echo and different use of quotes, and convinced myself that line really expands into what I want, but the only way I could actually get any output is with this:

#!/bin/bash
GREP="grep  -Hnr \"$1\" --include \"*cpp\" --include \"*h\" $2"
echo $GREP | bash

An example usage would be:

srcgrep "dynamic_cast" src

I've tried this in a simple example directory to rule out anything weird with links, permissions, etc. So, of course I can just use the second, but any idea what's wrong in the first case? Thanks.

$ grep -V
grep (GNU grep) 2.5.1
...

$ bash --version
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
...

Upvotes: 1

Views: 1650

Answers (2)

Ed Morton
Ed Morton

Reputation: 204731

So, GNU or someone's found a way to screw up grep with completely inappropriate options. Awesome. They really should have considered the UNIX philosophy of "Do one thing and do it well". grep is for searching for text in files, it's not for finding files. There's a perfectly good command with a somewhat obvious name for FINDing files.

find "$2" -name '*cpp' -o -name '*h' -exec grep -Hnr "$1" {} \;

assuming "$2" in your posted example is a directory name instead of a file name as you'd expect grep to work on.

Upvotes: 2

Marc B
Marc B

Reputation: 360922

Why not just:

#!/bin/bash
grep  -Hnr "$1" --include "*cpp" --include "*h" $2

?

Upvotes: 3

Related Questions