Reputation: 35848
Does anybody know what is the equivalent to $?
in Windows command line? Is there any?
EDIT: $?
is the UNIX variable which holds the exit code of the last process
Upvotes: 13
Views: 7304
Reputation: 5831
This Microsoft blog touches on the answer for both Cmd.exe
and PowerShell:
In CMD.exe
, you'll want to check the value of %ERRORLEVEL%
, here are some resources:
In PowerShell, use $?
:
Upvotes: 15
Reputation: 31
Sorry to dredge up an old thread, but it's worth noting that %ERRORLEVEL% doesn't get reset with every command. You can still test "positive" for errorlevel after several lines of subsequent--and successful--batch code.
You can reliably reset errorlevel to a clean status with ver
. This example works with UnxUtils for a more Linux-ish directory listing. The reset might seem extraneous at the end, but not if I need to call this script from another.
:------------------------------------------------------------------------------
: ll.bat - batch doing its best to emulate UNIX
: Using UnxUtils when available, it's nearly unix.
:------------------------------------------------------------------------------
: ll.bat - long list: batch doing its best to emulate UNIX
: ------------------------------------
: zedmelon, designer, 2005 | freeware
:------------------------------------------------------------------------------
@echo off
setlocal
: use the UnxUtil ls.exe if it is in the path
ls.exe -laF %1 2>nul
if errorlevel 1 (
echo.
echo ----- ls, DOS-style, as no ls.exe was found in the path -----
echo.
dir /q %1
)
: reset errorlevel
ver>nul
endlocal
Feel free to use this. If you haven't seen UnxUtils, check 'em out.
Upvotes: 3
Reputation: 17751
%ERRORLEVEL% Returns the error code of the most recently used command. A non zero value usually indicates an error.
http://technet.microsoft.com/en-us/library/bb490954.aspx
$? Contains True if last operation succeeded and False otherwise. And
$LASTEXITCODE Contains the exit code of the last Win32 executable execution.
http://blogs.msdn.com/powershell/archive/2006/09/15/ErrorLevel-equivalent.aspx
$? Expands to the exit status code of the most recently executed foreground program.
http://unix.sjcc.edu/cis157/BashParameters.htm
Upvotes: 11
Reputation: 5427
@echo off
run_some_command
if errorlevel 2 goto this
if errorlevel 1 goto that
goto end
:this
echo This
goto end
:that
echo That
goto end
:end
Upvotes: 1