0

I'm running a remote executable which produces a logfile.

I want to write a script to check whether the executable is run successfully or encounters an error. The way I can do this is by looking at the growing log file and seeing if the string "error" or "success" occurs first.

I know I can grep a file in realtime using

tail -f output.log | grep --line-buffered "string"

However, can I write a script which will tell me whether the grep for "error" or the grep for "success" occurs first?

3 Answers 3

0

Search for both strings using grep, extract the line numbers of the first match, and compare the values.

  • grep option -n gives the line number of any matches.
  • option -m1 lists only the first match then exits.
  • incidentally option -F fast grep - may be useful if no regular expressions are required in the search string.

An example output from the error grep will look something like - the line number 235 is to be extracted from the output.

235:[Wed Jun 04 12:23:19 2014] [error] child pid 6575 Segmentation fault (11)

The line numbers can be extracted by deleting the longest substring match %%:.* from the output to leave the numeric values which are compared in the if statement.

er_match=$(tail -f output.log | grep -n -F -m1 --line-buffered "error")
ok_match=$(tail -f output.log | grep -n -F -m1 --line-buffered "success")

if [[ ${er_match%%:.*} - gt ${ok_match%%:.*} ]];then
    echo "error first"
else
    echo "sucess first"
fi
0

You can do this by only looking at the first result returned by grep, for example with head -n1:

status=$(grep -o 'success\|error' output.log | head -n1)
if [[ $status == "success" ]]; then
    # Program started successfully
else
    # Program encountered an error
fi
2
  • Thanks, but I need something that will constantly check the file for "success" or "error" and return which one occurs first (in time)
    – Eddy
    Jun 11, 2014 at 11:39
  • @Eddy: I know too little about output.log to give a better answer. Can you provide more information? For example: How frequently do error and success occur? Do you have any control over when the program is run?
    – Thor
    Jun 11, 2014 at 11:58
0

If you use egrep you can check for either string on each line:

egrep 'success|failure'

This will bring out the lines in order, and you can pipe the output to something to select the first line.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .