Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script to trigger a command with every new line in to a file?

Is it possible to trigger a command with every new line in to a file?

For example: I have a log file say maillog. I want to get every new entry in to the log file as a mail.

If a new entry like " Mail Sent " added in to maillog file then my script should grep the new entry and send me a mail with the entry(data).

I know its crazy but i want to automate my Linux box with these kind of things.

Regards,

like image 403
puligilla Avatar asked Nov 30 '25 14:11

puligilla


1 Answers

Use tail -f, that watches a file and sents whatever is appended to it to stdout. If you have a script that performs the desired action, say mail_per_line, then you can set it up as

tail -f maillog | mail_per_line

In this case, mail_per_line runs once and gets all the lines. If you want to spawn a separate process each time a line comes in, use the shell built-in read:

tail -f maillog | while IFS='' read line; do
    send_a_message "$line"
done

To counter the effect described by Alfe, that a restart of this program will cause all the previous logs to be processed again, consider using logrotate.

like image 97
Fred Foo Avatar answered Dec 03 '25 09:12

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!