Ova

How to check return code in batch file?

Published in Batch Scripting 5 mins read

To check the return code (also known as the exit code or errorlevel) in a batch file, you primarily use the built-in %ERRORLEVEL% environment variable. This variable automatically stores the exit status of the most recently executed command.

Understanding %ERRORLEVEL%

The %ERRORLEVEL% environment variable holds an integer value that indicates whether the last command executed completed successfully or failed, and sometimes provides details about the nature of the failure.

  • 0 (Zero): Typically signifies successful execution.
  • Non-zero value (e.g., 1, 2, 5, etc.): Usually indicates that an error occurred or the command completed with a specific status. The meaning of specific non-zero codes varies depending on the command that set them.

How to Check %ERRORLEVEL%

You can evaluate %ERRORLEVEL% using the IF command in your batch script. There are two main ways to compare its value:

1. Using IF ERRORLEVEL N (Greater Than or Equal To)

The syntax IF ERRORLEVEL N checks if the current %ERRORLEVEL% is equal to or greater than the specified number N.

Syntax:

IF ERRORLEVEL N (
    REM Commands to execute if ERRORLEVEL is >= N
) ELSE (
    REM Commands to execute if ERRORLEVEL is < N
)

Example:

@echo off
DEL non_existent_file.txt
IF ERRORLEVEL 1 (
    ECHO A problem occurred trying to delete the file (ERRORLEVEL is %ERRORLEVEL%).
) ELSE (
    ECHO File deleted successfully.
)

In this example, if DEL fails (e.g., because the file doesn't exist), ERRORLEVEL will be a non-zero value (often 1). IF ERRORLEVEL 1 will catch any ERRORLEVEL of 1 or greater.

2. Using IF %ERRORLEVEL% <operator> N (Exact or Specific Comparison)

For exact comparisons, or when you need to check for specific non-zero values, you can directly compare %ERRORLEVEL% like any other environment variable using comparison operators.

Syntax:

IF %ERRORLEVEL% <operator> N (
    REM Commands to execute based on exact comparison
)

Common Comparison Operators:

Operator Description Example
EQU Equal to IF %ERRORLEVEL% EQU 0
NEQ Not equal to IF %ERRORLEVEL% NEQ 0
LSS Less than IF %ERRORLEVEL% LSS 5
LEQ Less than or equal to IF %ERRORLEVEL% LEQ 1
GTR Greater than IF %ERRORLEVEL% GTR 10
GEQ Greater than or equal to IF %ERRORLEVEL% GEQ 1

Example:

@echo off
REM Simulate a command that might return 0, 1, or 2
REM For demonstration, let's manually set ERRORLEVEL
VER >NUL 2>&1
IF %ERRORLEVEL% EQU 0 (
    ECHO Command succeeded (ERRORLEVEL is 0).
) ELSE IF %ERRORLEVEL% EQU 1 (
    ECHO Command failed with a generic error (ERRORLEVEL is 1).
) ELSE IF %ERRORLEVEL% GTR 1 (
    ECHO Command failed with a specific error code greater than 1 (ERRORLEVEL is %ERRORLEVEL%).
)

Setting Custom Return Codes with EXIT /B

You can define and return custom error codes from your batch script or from a subroutine within it using the EXIT /B command. This is especially useful for modular scripts where different parts of the script signal their outcome to the calling process.

The EXIT /B <exitcode> command exits the current batch script or subroutine and sets the %ERRORLEVEL% of the calling process to the specified <exitcode>.

Syntax:

EXIT /B <exitcode>

Example: Batch File Returning Custom Code

:: my_script.bat
@echo off

REM Simulate some operation
ECHO Performing some tasks...
REM Let's assume an error condition based on some logic
SET my_variable=fail

IF "%my_variable%"=="fail" (
    ECHO Task failed. Returning custom error code 5.
    EXIT /B 5
) ELSE (
    ECHO Task succeeded. Returning custom error code 0.
    EXIT /B 0
)

Example: Calling a Subroutine and Checking its Return Code

@echo off
ECHO Starting main script...

CALL :PerformAction
IF %ERRORLEVEL% EQU 0 (
    ECHO Main script: Action completed successfully.
) ELSE IF %ERRORLEVEL% EQU 1 (
    ECHO Main script: Action failed with a generic error.
) ELSE IF %ERRORLEVEL% EQU 5 (
    ECHO Main script: Action failed with specific error 5.
) ELSE (
    ECHO Main script: Action failed with unknown error %ERRORLEVEL%.
)

GOTO :EOF

:PerformAction
REM This subroutine will perform an action and return a code
ECHO   Subroutine: Executing action...

REM Simulate a command that might fail (e.g., trying to find a non-existent file)
FIND "nonexistent" "nonexistent.txt" >NUL 2>&1
IF %ERRORLEVEL% NEQ 0 (
    ECHO   Subroutine: Find command failed. Returning 1.
    EXIT /B 1
)

REM Simulate another condition
SET /A RANDOM_NUM=%RANDOM% %% 2
IF %RANDOM_NUM% EQU 0 (
    ECHO   Subroutine: Specific condition met. Returning 5.
    EXIT /B 5
)

ECHO   Subroutine: Action completed without specific issues. Returning 0.
EXIT /B 0

Chaining Commands with Conditional Execution

Batch files also support && and || operators for conditional execution based on the ERRORLEVEL of the preceding command:

  • && (AND): Executes the next command only if the previous command succeeded (returned ERRORLEVEL 0).
  • || (OR): Executes the next command only if the previous command failed (returned a non-zero ERRORLEVEL).

Example:

@echo off
COPY existing_file.txt new_file.txt && ECHO File copied successfully || ECHO File copy failed

This line attempts to copy existing_file.txt. If the copy is successful, it will ECHO "File copied successfully". If it fails, it will ECHO "File copy failed".

Key Considerations

  • Most Recent Command: Remember that %ERRORLEVEL% is updated after every command. If you need to check the ERRORLEVEL of a specific command, do so immediately after that command before executing others.
  • External Programs: When you run external executable programs (.exe) from a batch file, they also set the ERRORLEVEL upon their exit.
  • SetLocal/EndLocal: If you use SETLOCAL to manage environment variables, changes to ERRORLEVEL within that scope will generally be preserved when ENDLOCAL is reached, affecting the ERRORLEVEL of the parent scope.

By leveraging %ERRORLEVEL% and EXIT /B, you can create robust batch scripts that can react intelligently to the success or failure of various operations. For more detailed information on batch commands, refer to the Microsoft Command Line reference.