Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search in logfile - exit code

I have some legacy softwares that I need to automate under Control-M. These job are under Windows 2008R2.

These jobs have an exit code 0 if they run ok, but also if they can manage some errors. I need to raise an alarm when a specific string is in the log.
The string is not in the output of executable.

I implemented another job for this. It goes to search a string inthe file and in "On Do Actions" I search for the statement.

To have the statement in the output I think to use something like a grep. I used:

  • findstr

    findstr "myerrorcode" D:\Log\greptest_%%$ODATE..log
    
  • grep under cygwin

In both case I have an identical situation:

  • If the string is found, everythings is ok
  • If the file is not found or cannot be open, grep or findstr return an exit code = 1. This is ok, because the job has to raise an error.

But the problem is: when the string is not found in the file, both grep and findstr have a return code = 1.

How can I discriminate the cases when the file cannot be open and when everything runs ok, but the sring in the log is not found?

like image 992
user_0 Avatar asked Jan 18 '18 17:01

user_0


1 Answers

You should be able to use grep's exit status to detect the reason for failure. According to the POSIX grep docs, exit status section:

EXIT STATUS

   The following exit values shall be returned:

   0    One or more lines were selected.
   1    No lines were selected.
   >1   An error occurred.

It's similar for GNU grep (consistent, but more specific):

Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. [...] Other grep implementations may exit with status greater than 2 on error.

For example, in bash, you could use the case command to handle multiple branches like this:

#!/bin/bash

# search for error code in file
grep code file

# store the exit status in variable err
err=$?

# test several cases
case $err in
    0) echo All good.;;
    1) echo Code not found.;;
    *) echo Error reading from file.;;
esac
like image 89
randomir Avatar answered Nov 03 '22 22:11

randomir