How to do something with bash when a text string appears in a file

I want to run the command as soon as certain text appears in the log file. How to do it in bash?

+4
source share
5 answers

Use command

tail -f file.log | grep --line-buffered "my pattern" | while read line do echo $line done 

Here --line-buffered is the key, otherwise reading will fail.

+14
source

Using tail only:

 tail -f file.log | while read line; do if [[ $line == *text* ]]; then mycommand fi; done 
+5
source

This should work even without GNU grep:

 tail -f -n 0 logfile.out | nawk '/pattern/ {system("echo do something here")}' 

edit: Added "-n 0", so only new occurrences of the text will be matched.

+1
source

You can also see inotail , a replacement for tail -f that uses the inotify framework to wake up only when the file you are interested in has changed. Regular tail -f just sleeps for short periods between polls, which is an effective but not very effective solution.

+1
source

I like matli's answer. Bruno De Fraine's answer is also good in that it uses only shell command commands and not other programs (like awk). He suffers from the problem that the whole line must match the magic line. It is not clear from the question what part of the requirement is.

I would modify it a bit to deal with the "as soon as" sentence in the original question

 logfile_generator | tee logfile.out | nawk '/pattern/ {system("echo do something here")}' 

where logfile_generator is the program that first creates the log file. This modification does "something" as soon as the magic string is found.

0
source

Source: https://habr.com/ru/post/1277351/


All Articles