Reputation: 15
I have log file that is generated in below format. I want to grep the log every 2 minutes and check for error using shell script how Can I get this? Any help would be greatly appreciated.
[12:17:02.1274]
[12:18:01.1976]
[12:18:01.2151]
[12:18:01.2152]
[12:18:01.4607]
[12:18:02.6306]
[12:18:03.7299]
[12:18:04.0307]
[12:18:04.1388]
[12:18:04.2068]
[12:18:06.4002]
[12:18:07.5805]
[12:19:01.8559]
[12:19:08.9950]
[12:19:09.2851]
[12:19:10.4704]
[12:19:12.8167]
[12:20:01.8968]
[12:20:01.9206]
[12:20:01.9206]
[12:20:02.1707]
[12:20:02.3064]
[12:20:05.4461]
[12:20:13.7205]
[12:20:14.0807]
[12:20:14.2360]
[12:20:17.3764]
[12:21:01.2299]
[12:21:10.4769]
[12:21:18.8085]
[12:21:19.1106]
[12:21:19.2456]
[12:21:22.3663]
Upvotes: 1
Views: 1105
Reputation: 1197
You can use the sleep function.
Try e.g.:
#!/bin/bash
echo start
sleep 2
echo end
Which will wait 2 seconds between the two echo commands.
Your complete script could be:
#!/bin/bash
while [ 1 ]; do
sleep 2m
if grep -qvE "^\[[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{4}\]" logfile.dat
then
echo "ERROR"
else
echo "Everything is fine..."
fi
done
The while-loop is always running because 1
is true
. In this infinite loop each two minutes (2m
) the check is done.
edit
I updated the code so that the data structure you were given is parsed. I use grep
with
-E
to enable the usage of regex-v
to match only the inverse (meaning that it searches for your structure and is actually grepping if this pattern isn't matching)-q
to use quiet mode and exit immediately if a match is foundIf your logfile.dat is not exactly of the style you were giving, grep is matching and ERROR is written to STDOUT
which typically is your terminal.
Upvotes: 1
Reputation: 10039
sed -n "$ s/\[\([0-9.:]*\)\].*/\1/p" | read Marker
while [ 1 ]
do
sleep 120
sed -n "$ s/\[\([0-9.:]*\)\].*/\1/p" | read NewMarker
sed -n "/${Marker/,/${NewMarker}/ p"
Marker="${NewMarker}"
done
it just print Twice the marker value (1 at last cylcle as last line) and one at current cycle as 1s line. It can be modified by replacing p
with /${Marker}/ !p
.
May not work if log is never close (if no EOF occur) because sed wait until that without explicit exit.
Upvotes: 0