Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.cmd and .bat file converting return code to an error message

I'm trying to automate a program I made with a test suite via a .cmd file.

I can get the program that I ran's return code via %errorlevel%.

My program has certain return codes for each type of error.

For example:

1 - means failed for such and such a reason

2 - means failed for some other reason

...

echo FAILED: Test case failed, error level: %errorlevel% >> TestSuite1Log.txt

Instead I'd like to somehow say:

echo FAILED: Test case failed, error reason: lookupError(%errorlevel%) >> TestSuite1Log.txt

Is this possible with a .bat file? Or do I have to move to a scripting language like python/perl?

like image 600
Brian R. Bondy Avatar asked Sep 24 '08 22:09

Brian R. Bondy


People also ask

How do I change the return code in a batch file?

It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file. EXIT /B at the end of the batch file will stop execution of a batch file. Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes.

Are .bat and .cmd files the same?

BAT is the batch file that is used in DOS, OS/2 and Microsoft Windows. CMD files are newer version came into existence for batch files. The older systems will not know about CMD files and will run them partially which will throw an error for the batch files saved as CMD.

How do I make a batch file terminate upon encountering an error?

Check the errorlevel in an if statement, and then exit /b (exit the batch file only, not the entire cmd.exe process) for values other than 0.


1 Answers

You can do this quite neatly with the ENABLEDELAYEDEXPANSION option. This allows you to use ! as variable marker that is evaluated after %.

REM Turn on Delayed Expansion
SETLOCAL ENABLEDELAYEDEXPANSION

REM Define messages as variables with the ERRORLEVEL on the end of the name
SET MESSAGE0=Everything is fine
SET MESSAGE1=Failed for such and such a reason
SET MESSAGE2=Failed for some other reason

REM Set ERRORLEVEL - or run command here
SET ERRORLEVEL=2

REM Print the message corresponding to the ERRORLEVEL
ECHO !MESSAGE%ERRORLEVEL%!

Type HELP SETLOCAL and HELP SET at a command prompt for more information on delayed expansion.

like image 165
Dave Webb Avatar answered Sep 21 '22 07:09

Dave Webb