Phani K
Phani K

Reputation: 1193

Building grep strings dynamically

I am writing a shell script to do a "tail" on a growing log file. This script accepts parameters to search for, and incrementally greps the output on them.

For example, if the script is invoked as follows:

logs.sh string1 string2

it should translate to:

tail -f logs.txt | grep string1 | grep string2

I am building the list of grep strings like this:

full_grep_string=""
for grep_string in $*
do
    full_grep_string="$full_grep_string | grep $grep_string" 
done

The string is built correctly, but when I try to finally tag it to the tail command, like so...

tail -f $LOG_FILE_PATH $full_grep_string

...the grep does not apply, and I get the unfiltered logs.

Am I missing something here? Or is there an easier way to do this?

Upvotes: 4

Views: 2023

Answers (2)

tuergeist
tuergeist

Reputation: 9391

grep buffers the line it found. So modifying your code to

full_grep_string="$full_grep_string | grep --line-buffered $grep_string" 

shall work. I tested it on debian lenny (with bash).

And use the tip of an0

eval tail -f ...

(All this works for whole words)

Upvotes: 1

an0
an0

Reputation: 17530

eval tail -f $LOG_FILE_PATH $full_grep_string

Upvotes: 2

Related Questions