Linux: track a file and send an email when a particular text shows up
Assume that you have to solve the following problem, you have to constantly watch a log file for a specific event and then send an email…
Assume that you have to solve the following problem, you have to constantly watch a log file for a specific event and then send an email, after sending the email you want to keep monitoring the file for new events, this is a very common issue and there are numerous tools to implement this but in our case we will do it the simplest way possible! using only basic bash tools!
Creating the file that we want to monitor
Open your terminal and enter the following command, ensure that you don't have the same filename in your directory, or else will be filled with unwanted data
touch hello.txtMonitoring the file
Enter the following line in the terminal, this will start monitoring file hello.txt for lines containing a string error and mail the line to example@example.com with the subject of hostname and the timestamp that the string found
tail -F ./hello.txt | while read line; do echo "$line" | grep -i 'error'| mailx -s "$(hostname) Error Found $(date)" example@example.com ; doneHow it works
- tail -F monitors the file for new lines and pipes output to the next command
- while read line; do this is a loop where each incoming line from the file will be fed to grep to check if
errorstring exists - if exists will be fed to mailx to be sent as an email body with a subject that contains the hostname and the date
Conclusion
In this article, we saw how we can use basic Linux commands to create smart and easy solutions like how to monitor files for specific content and send an email upon its appearance