Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the application exit code from a Windows command line?

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?

like image 721
Skrud Avatar asked Dec 02 '08 18:12

Skrud


People also ask

How do I get the exit code from the last command?

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.

How do I get an exit code?

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.

Which command is used to exit the application?

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.


2 Answers

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.

Example

@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.

like image 147
DrFloyd5 Avatar answered Sep 22 '22 11:09

DrFloyd5


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% 
like image 21
Gary Avatar answered Sep 19 '22 11:09

Gary