Shell Script Find in File

Right, noob to shell scripting, playing a round for practice, wrote the following but it doesn't seem to work as expected, how could I fix/improve this script?

#!/bin/bash
#set -v
#set -x

case $# in
1)
echo Searching for $1 in '*';
find . -iname '*' 2>/dev/null | xargs grep "$1" -sl 2>/dev/null;;
2)
echo Searching for $1 in $2;
find . -iname "$2" 2>/dev/null | xargs grep "$2" -sl 2>/dev/null;;
3)
echo Searching for $1 in $2 in dir $3;
find "$3" -iname "$2" 2>/dev/null | xargs grep "$1" -sl 2>/dev/null;;
*)
echo =Find in file=;
echo Usage $0 String [FileName] [FileDir];;

esac

-iname '*' is redundant, leave it out and find does the same thing. find finds everything unless you tell it not to.

You might also want to add -type f to all your find calls to prevent you doing things like grepping on directories and such. That should eliminate most of the errors you had to redirect into /dev/null.

I notice for your second option you have grep "$2" instead of grep "$1" which I think is a mistake. Your search string is always your first parameter.

Beyond that, in what ways is it operating not as expected?

Otherwise: Your script looks pretty sane and even rather efficient. You even got xargs working right, which baffles most people new to shell scripting.

Glad I got some things right

I've now updated the code to:

#!/bin/bash
#set -v
#set -x

case $# in
1)
echo Searching for $1 in '*';
find . -type f 2>/dev/null | xargs grep "$1" -sl 2>/dev/null;;
2)
echo Searching for $1 in $2;
find . -type f -iname "$2" 2>/dev/null | xargs grep "$1" -sl 2>/dev/null;;
3)
echo Searching for $1 in $2 in dir $3;
find "$3" -type f -iname "$2" 2>/dev/null | xargs grep "$1" -sl 2>/dev/null;;
*)
echo =Find in file=;
echo Usage $0 String [FileName] [FileDir];;

esac

Things that don't work as expected

oak204b:bin john$ fif test '*' /
Searching for test in 2to3 2to32.6 RSA_SecurID_getpasswd a2p a2p5.10.0 a2p5.8.9 aaf_install addftinfo afconvert afinfo afmtodit afplay afscexpand
alias allmemory amavisd amavisd-agent amavisd-nanny amavisd-release ant applesingle appletviewer apply apr-1-config apropos apt etc....

And I still get permission errors

find: ./.fseventsd: Permission denied
find: ./.Spotlight-V100: Permission denied
find: ./.Trashes: Permission denied

In what way is it not expected?

I'm guessing you mean that it shows all the filenames? That's because you didn't quote $2 so it expands in the shell becoming all the names. * has a special meaning in the shell too. Quote it like "$2" to stop it expanding.

Oh well, I guess you really do have some dirs you don't have access to. The -type f should help reduce the number anyway, and the redirection will take care of it like you had before.