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?
Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.
To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.
In computing, exit is a command used in many operating system command-line shells and scripting languages. The command causes the shell or program to terminate.
A pseudo environment variable named errorlevel
stores the exit code:
echo Exit Code is %errorlevel%
Also, the if
command has a special syntax:
if errorlevel
See if /?
for details.
@echo off my_nify_exe.exe if errorlevel 1 ( echo Failure Reason Given is %errorlevel% exit /b %errorlevel% )
Warning: If you set an environment variable name errorlevel
, %errorlevel%
will return that value and not the exit code. Use (set errorlevel=
) to clear the environment variable, allowing access to the true value of errorlevel
via the %errorlevel%
environment variable.
Testing ErrorLevel
works for console applications, but as hinted at by dmihailescu, this won't work if you're trying to run a windowed application (e.g. Win32-based) from a command prompt. A windowed application will run in the background, and control will return immediately to the command prompt (most likely with an ErrorLevel
of zero to indicate that the process was created successfully). When a windowed application eventually exits, its exit status is lost.
Instead of using the console-based C++ launcher mentioned elsewhere, though, a simpler alternative is to start a windowed application using the command prompt's START /WAIT
command. This will start the windowed application, wait for it to exit, and then return control to the command prompt with the exit status of the process set in ErrorLevel
.
start /wait something.exe echo %errorlevel%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With