user2569831
user2569831

Reputation:

Bash Script - tail to file

I have the following in a bash script file watcher.sh.

grep ERROR $ExampleLogFile > $ErrorLogFile

When I run this, it copied the lines from ExampleLogFile to ErrorLogFile that contain ERROR successfully.

I need to make it so it continually monitors the ExampleLogFile for changes and writes those to the ErrorLogFile.

I was thinking of doing the following, but this doesn't work:

tail -f grep ERROR $ExampleLogFile > $ErrorLogFile

It does write some of the lines, but its not the ones containing ERROR.

tail: grep: No such file or directory
tail: ERROR: No such file or directory

Any advise please.

Upvotes: 0

Views: 765

Answers (4)

Max
Max

Reputation: 405

You need:

while :; do grep ERROR $ExampleLogFile > $ErrorLogFile; sleep 2; done

This should achieve what you want without needing the tail command.

If the file will ever be cleared though this will not work as you might expect because the grep will pull only current entries in the $ErrorLogFile.

Upvotes: 0

Akhil
Akhil

Reputation: 1040

You can use tee command here.

tail -f $ExampleLogFile | grep --line-buffered  ERROR | tee $ErrorLogFile

It will store and print to stdout at the same time.

enter image description here

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 140960

tail -f $ExampleLogFile | grep --line-buffered ERROR > $ErrorLogFile

or paranoic:

stdbuf -oL tail -f $ExampleLogFile | stdbuf -oL grep --line-buffered ERROR > $ErrorLogFile

But most probably you want to include existing lines too. In that case:

tail -n +1 -f $ExampleLogFile | grep --line-buffered ERROR > $ErrorLogFile

Upvotes: 0

dash-o
dash-o

Reputation: 14432

You can arrange the tail/grep in a pipe

tail -f $ExampleLogFile | grep ERROR  > $ErrorLogFile

Remember that this command will never exit by itself (tail will continue to look for additional data). You will have to arrange for some other exit condition (e.g., timeout, explicit kill, etc).

Upvotes: 0

Related Questions