Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do something with Bash when a text line appears in a file

Tags:

linux

grep

bash

I want to run a command as soon as a certain text appears in a log file. How do I do that in Bash?

like image 441
ketorin Avatar asked Nov 30 '22 20:11

ketorin


2 Answers

Use command

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

The --line-buffered is the key here, otherwise the read will fail.

like image 155
ketorin Avatar answered Dec 04 '22 05:12

ketorin


Using only tail:

tail -f file.log | while read line; do if [[ $line == *text* ]]; then
    mycommand
fi; done
like image 41
Bruno De Fraine Avatar answered Dec 04 '22 05:12

Bruno De Fraine