ae.
ae.

Reputation: 1680

Bash alias query

How can I turn the following command into a bash alias?

find . -name '*.php' | xargs grep --color -n 'search term'

Where I can specify the file extension and 'search term' is obviously the search term :)

So what I want to do is:

 searchFiles 'php' 'search term'

How do I pass the input into the alias? Should I just create a bash script and have the alias point to the script?

Upvotes: 5

Views: 2891

Answers (4)

Andy Lester
Andy Lester

Reputation: 93666

Shell functions are good, but you may also want to take a look at ack. It handles file-specific searching, with color-coding, so that your example would simply be

ack --php somepattern

Upvotes: 1

Gonzalo
Gonzalo

Reputation: 21175

How about using a function? Add this to your .bashrc:

function searchFiles() {
       find . -name \*."$1" -print0 | xargs -0 grep --color -n "$2"
}

and then use it like:

$ searchFiles c include

Upvotes: 8

Roger Pate
Roger Pate

Reputation:

While a function works, it won't be callable from other programs and scripts (without a lot of pain). (An alias would have the same problem.) A separate script would be my choice, since it sounds like you want to invoke it directly:

#!/bin/bash
# since you're already using bash, depend on it instead of /bin/sh
# and reduce surprises later (you can always come back and look at
# porting this)

INCLUDE="*.$1"
PATTERN="$2"
grep --color -n "$PATTERN" --recursive --include="$INCLUDE" .

(No need for find with what you have.)

If this was only used inside another script instead of directly, a function would be easier.

Upvotes: 1

Chris Johnsen
Chris Johnsen

Reputation: 224691

You could use an alias, but using a function, like Gonzalo shows, the sane thing to do.

alias searchFiles=sh\ -c\ \''find . -name \*."$1" -type f -print0 | xargs -0 grep --color -Hn "$2"'\'\ -

Whether function or alias, I recommend using -print0 with find and -0 with xargs. This provides for more robust filename handling (most commonly, spaces in filenames).

Upvotes: 5

Related Questions