QUESTION
I have a server log that outputs a specific line of text into its log file when the server is up. I want to execute a command once the server is up, and hence do something like the following:
tail -f /path/to/serverLog | grep "server is up" ...(now, e.g., wget on server)?
What is the best way to do this?
ANSWER
A simple way would be awk.
tail -f /path/to/serverLog | awk '/Printer is on fire!/ { system("shutdown -h now") }
/new USB high speed/ { system("echo New USB" | mail admin")'
And yes, both of those are real message from a kernel log. Perl might be a little more elegant to use for this and can also replace the need for tail. If using perl, it will look something like this:
open(my $fd, "<", "/path/to/serverLog") or die "Can't open log";
while(1) {
if(eof $dataFd) {
sleep 1;
$fd->clearerr;
next;
}
my $line = <$fd>;
chomp($line);
if($line =~ /Printer is on fire!/) {
system("shutdown -h now");
} elsif($line =~ /new USB high speed/) {
system("echo New USB" | mail admin");
}
}
Tweet