Passing regular expression as parameter [duplicate]

I am trying to pass a regular expression as a parameter. What should I fix in my code? My goal is to send find and the regular expression string, then use grep on the parameter so I can do whatever I want with what grep finds (which is print the count of occurrences).

This is what I send:

$ ./lab12.sh find [Gg]reen

Here's my bash code:

if [[ "$1" == "find" ]]
then
    declare -i cnt=0
    for file in /tmp/beatles/*.txt ; do
        if [[ grep -e $2 ]]  //problem is here...
        then
            ((cnt=cnt+1))
        fi
    done
    echo "$cnt songs contain the pattern "$2""
fi        

Solution 1:

The if statement takes a command. [[ being one, and grep is another, writing [[ grep ... ]] is essentially as wrong as writing vim grep, or cat grep etc, just use:

if grep -q -e "$pattern"
then
  ... 

instead.

The -q switch to grep will disable output, but set the exit status to 0 (success) when the pattern is matches, and 1 (failure) otherwise, and the if statement will only execute the then block if the command succeded.

Using -q will allow grep to exit as soon as the first line is matches.

And as always, remember to wrap your paremeter expansions in double quotes, to avoid pathname expansion and wordsplitting.

Note that square brackets [...] will be interpreted by your calling shell, and you should escape them, or wrap the whole pattern in quotes.

It's always recommended use single quotes, as the only special character is another single quote.

$ ./lab12.sh find '[Gg]reen'