I am running a program and want to see what its return code is (since it returns different codes based on different errors).
I know in Bash I can do this by running
echo $?
What do I do when using cmd.exe on Windows?
The "exit code" is stored in a shell variable named errorlevel
.
The errorlevel
is set at the end of a console application. Windows applications behave a little differently; see @gary's answer below.
Use the if
command keyword errorlevel
for comparison:
if errorlevel <n> (<statements>)
Which will execute statements when the errorlevel is greater than or equal to n. Execute if /?
for details.
A shell variable named errorlevel
contains the value as a string and can be dereferenced by wrapping with %'s.
Example script:
my_nifty_exe.exe
rem Give resolution instructions for known exit codes.
rem Ignore exit code 1.
rem Otherwise give a generic error message.
if %errorlevel%==7 (
echo "Replace magnetic tape."
) else if %errorlevel%==3 (
echo "Extinguish the printer."
) else if errorlevel 2 (
echo Unknown Error: %errorlevel% refer to Run Book documentation.
) else (
echo "Success!"
)
Warning: An environment variable named errorlevel, if it exists, will override the shell variable named errorlevel. if errorlevel
tests are not affected.