Home > Software design >  How to not generate ERRORLEVEL 1 on findstr
How to not generate ERRORLEVEL 1 on findstr

Time:02-04

I'm building a validation for my jobs on Jenkins to see if today is a holiday. I have a .csv file with the dates that is holiday, I just need to see if today is on this file.

For this in CentoOs I use the following code that works great:

    TODAY="`date  %d/%m/%Y`"
if  grep -qF $TODAY /home/holiday.csv; then   
    echo "ITS HOLIDAY, DONT RUN NOTHING"
    exit 0
else
    echo "ITS NOT HOLIDAY, RUN SOMETHING!"
fi

But for the Jobs that run on Windows I was searching for a equivalent of "grep" and found "findstr". Works pretty similar, but there is a problem, I just found validations with "ERRORLEVEL 1". My code is:

for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x

set TODAY=%MyDate:~6,2%/%MyDate:~4,2%/%MyDate:~0,4%

findstr %TODAY% C:\holiday.csv

IF ERRORLEVEL 1 (echo "ITS NOT HOLIDAY, RUN SOMETHING!") ELSE (echo "ITS HOLIDAY, DONT RUN NOTHING")

The problem is, for Jenkins if the code returns ERRORLEVEL 1, the code has a error and Jenkins flag the execution with error, but in this situation there is no problem, because "not found == not holiday" (sure, for findstr is a error, but you guys get it).

Other problem is, I found that I just can put a "exit 0" and the job will not flag as a error, but if I do this the thing that will be on ' echo "ITS NOT HOLIDAY, RUN SOMETHING!" ' we will never know if has error or not (I can see on jenkins log, but its more intuitive if the execution show the correct result".

So, what can I do?

CodePudding user response:

I suspect OP has oversimplified the situation, and the actual code is

IF ERRORLEVEL 1 (echo "ITS NOT HOLIDAY, RUN SOMETHING!"
                 ask_mr_jenkins_something
                ) ELSE (echo "ITS HOLIDAY, DONT RUN NOTHING")

echo does not clear errorlevel, hence Jenkins sees errorlevel=1 when it starts.

To force errorlevel to 0, try

IF ERRORLEVEL 1 (echo "ITS NOT HOLIDAY, RUN SOMETHING!"
                 ver>nul
                 ask_mr_jenkins_something
                ) ELSE (echo "ITS HOLIDAY, DONT RUN NOTHING")

ver reports the version number (no doubt you don't want to see that, hence >nul to suppress the report) and sets errorlevel to 0.

  •  Tags:  
  • Related