Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Inside a batch file on Windows, I use 7-zip like this:

...\right_path\7z a output_file_name.zip file_to_be_compressed

How could I check the exit code of 7z and take the appropriate action ?

share|improve this question
    
Also asked on Stackoverflow: How do I get the application exit code from a Windows command line? –  Deanna Jun 24 '13 at 11:42

2 Answers 2

up vote 36 down vote accepted

Test for a return code greater than or equal to 1:

if ERRORLEVEL 1 echo Error

or

if %ERRORLEVEL% GEQ 1 echo Error

or test for a return code equal to 0:

if %ERRORLEVEL% EQU 0 echo OK

You can use other commands such as GOTO where I show echo.

share|improve this answer
    
I tried your code. I got the following error: 0 was unexpected this time. –  Misha Moroshko Oct 1 '10 at 5:13
2  
@Misha: You may have tried it with the percent signs the way I originally posted it. Try it without them or try the other versions I added. –  Dennis Williamson Oct 1 '10 at 5:24
    
Great, thanks a lot !! –  Misha Moroshko Oct 1 '10 at 11:53

This really works when you have: App1.exe calls -> .bat which runs --> app2.exe

App2 returns errorlevel 1... but you need to catch that in the .bat and re-raise it to app1... otherwise .bat eats the errorlevel and app1 never knows.

Method:

In .bat:

app2.exe
if %ERRORLEVEL% GEQ 1 EXIT /B 1

This is a check after app2 for errorlevel. If > 0, then the .bat exits and sets errorlevel to 1 for the calling app1.

share|improve this answer
2  
it could be even better if you returned the same error back to app1. i didn't try this out, but it should work : if %ERRORLEVEL% GEQ 1 EXIT /B %ERRORLEVEL%. –  Viktor Fonic Jul 18 at 11:24
    
At least in Windows, %ERRORLEVEL% can be a negative number (e.g. I have a program that returns -1 on errors). IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL% might be a better option. But you really need to know what the program returns on errors. Some programs return certain non-zero codes for special types of success. –  Euro Micelli Nov 13 at 19:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.