Reputation: 23
Completely clueless with Bash, but trying to learn to accomplish this single task.
I need a script that can tail the last 50 lines of a logfile, looking for the string "ERROR", and send an email if that condition is true.
I can do bits and pieces manually, but am not able to build something that works completely to stick in a cron. Sendmail works by itself.
tail -n 50 /var/log/unifi-video/recording.log | grep ERROR
works to at least output that. Ideally I'd like an email only if ERROR is found in the last 50 lines, else no action needs to be taken. If anyone can assist with the if/else statement to make this happen, it would be greatly appreciated.
Upvotes: 2
Views: 5714
Reputation: 532043
grep
exits with status 0 if a match is found, 1 if not, so something like
tail -n 50 /var/log/unifi-video/recording.log | grep -q ERROR && <sendmail command here>
would do what you want. (The -q
option suppresses any output, because you don't care what line actually matched, just that a match was found.)
Upvotes: 0
Reputation: 50218
If you are looking to do this in a one liner you could use something like:
[ $(tail -n 50 /var/log/unifi-video/recording.log | grep ERROR | wc -l) -gt 0 ] && yourmailcommand
This just pipes the output of your grep
to wc -l
which returns how many lines are returned from grep. If that count is greater than 0 then it will execute that bit after the double ampersands. If you want to include an else
in the event that no ERROR
lines are found you could:
[ $(tail -n 50 /var/log/unifi-video/recording.log | grep ERROR | wc -l) -gt 0 ] && yourmailcommand || dosomethingelseinstead
Upvotes: 1