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?

3
  • 6
    Try dropping the $args and just saying grep "$@" /path/to/logs/my.log.
    – Tom Hunt
    Oct 20, 2015 at 17:06
  • 5
    You might also be interested in What is the difference between $* and $@?
    – terdon
    Oct 20, 2015 at 17:33
  • 1
    Not a noobish question at all. This trips up even vets, and at least you did your homework.
    – coteyr
    Oct 20, 2015 at 19:09

1 Answer 1

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.

1
  • This works perfectly, thanks! Also thanks to everyone who responded so cordially and helpfully. Oct 22, 2015 at 21:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .