6

I'm trying make a function that simplifies grepping a log I have to work with on a regular basis.

I'd like to use extended regexp with it pipe and redirect the output, etc.

But I'm having trouble doing this using the standard grep pattern file syntax in the function.

The way I have it set up now is horrible to look at, but gets the job done:

alias mygrep='cat /path/to/logs/my.log | grep'

This allows me to run the following without trouble

mygrep -i -E "WARN|java" |less

Seems like the correct implementation should be something like the following.

function mygrep () {
    args=$*
    grep "$args" /path/to/logs/my.log
}

However when I use this with the search and pipe parameters above, grep returns an invalid option error.

What am I missing?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

1 Answers1

11

The following code has $args quoted:

grep "$args" /path/to/logs/my.log

This asks to pass the entire value of that variable as a single parameter to grep. Thus, if you call mygrep with parameters -i and -E, grep will in fact receive a single parameter -i -E, which is indeed invalid.

The following should do it:

function mygrep () {
    grep "$@" /path/to/logs/my.log
}

Writing "$@" does the right thing: it's similar to $*, except that it properly expands each parameter to a single word.

dhag
  • 15,736
  • 4
  • 55
  • 65