When at the command line, I find that I have to type out this command very often:

find . -iname "*php" -exec grep -H query {} \;

I'd love to set up an alias, script, or shortcut to make it work easier. I would like to do something like:

mysearch query ("*php") (.)

It would be great if the command could accept three arguments, in reverse order:

query string, file name expression, directory

If the second two arguments were omitted they would default to not being included, and the current directory.

Finally, the icing on the cake would be that if additional variables were included (4th, 5th, 6th...) they would be injected as additional arguments for the find command (like I could say -type d) at the end.

Attempted code

I tried the example below, but I'm still having trouble setting default values. What am I doing wrong?

#!/bin/bash
c=${param1+\.}
b=${param2+\*}
a=${param3+test}
find $c -iname $b -exec grep -H $a {} \;
link|improve this question

feedback

1 Answer

up vote 1 down vote accepted

Make a shell script and add it to your PATH:

#!/bin/bash
find $3 -iname $2 -exec grep -H $1 {} \;

Name it mysearch, make it executable chmod +x mysearch, verify that it works, and add it to your path:

source

More info about parameters in bash

Edit /home/you/.bash_profile and add your script there. It should work when you type mysearch x x x. You might want to make defaults for each parameter. It's pretty easy, here's a how-to for basic and advanced uses.

EDIT: Bash param basics:

Parameters in bash are of the form $1 $2 $3, where $1 is the first parameter that you care about. There is actually a $0, but this is the name of your script as it appears on the commandline when you call it, so it isn't that important.

PARAM1=$1 PARAM2=$2

You were pretty close. Instead of c=${param1+\.} it should be: c=${1:-"."} (I think you can leave off the quotes, but it's easier to tell what a string is if you have them).

I would also do ${c} instead of $c because sometimes you need the braces, but it will never be wrong to put them everywhere.

link|improve this answer
I'm having trouble setting up default values, even after reading the documentation. Any tips? – cwd Apr 6 '11 at 0:19
I edited my answer to show how to do defaults. (you need a :- instead of a +). – tjameson Apr 6 '11 at 2:48
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.