The && operator in Windows Command Prompt executes the subsequent command only if the preceding command returns an exit code of zero. If you observe a command running despite %ErrorLevel% being 99, it is likely because you are using the if errorlevel syntax incorrectly or relying on delayed expansion improperly. The && chain itself does not read %ErrorLevel% directly; it checks the raw exit status of the previous process.
Understanding Exit Codes and the && Operator
In Windows Batch scripting and Command Prompt, every executable program returns an integer known as an exit code or return value. By convention, an exit code of 0 indicates success, while any non-zero value indicates an error or a specific failure state. The&& (AND) operator is a logical chaining mechanism that evaluates the left-hand side first. If the left-hand side succeeds (exit code 0), the right-hand side is executed. If the left-hand side fails (non-zero exit code), the right-hand side is skipped entirely.
This behavior is fundamentally different from how many other programming languages handle boolean logic. In C or Python, you might expect a variable to hold a "true" or "false" state. In CMD, there is no such implicit boolean conversion for general commands. The && operator looks strictly at the numeric exit code. If your script shows a command running when you believe it should not, verify that the command preceding the && actually returned a non-zero code. Sometimes, internal cmd.exe commands like echo or set may behave unexpectedly if not quoted properly, leading to a false sense of success.
For more details on how command chaining handles these return values, see our guide on Windows Command Prompt: Command Chaining and Non-Zero Return Values. This resource explains the nuances of how different operators interact with system states.
The Role of %ErrorLevel%
The environment variable%ErrorLevel% stores the exit code of the last executed program. It is crucial to understand that %ErrorLevel% is just a string representation of a number. When you use &&, you are not checking the content of this variable; you are checking the kernel's exit status. However, if you are writing complex scripts, you often need to check %ErrorLevel% explicitly using the if statement.
A common mistake is assuming that %ErrorLevel% is automatically updated by every single character typed. It is only updated after a command finishes. Furthermore, if you use call to invoke another batch file, the %ErrorLevel% will be overwritten by the called script unless you capture it immediately. Always test your exit codes using echo %ErrorLevel% immediately after the command runs to ensure you are seeing the correct value before making logical decisions.
Why Commands Run Despite High Error Levels
If you have verified that%ErrorLevel% is 99, yet the next command in an && chain still runs, several technical issues could be at play. First, ensure that you are not inadvertently using the | (pipe) or || (OR) operator instead of &&. The || operator runs the next command only if the previous one failed. If you meant to stop execution on failure but used ||, the command would run precisely when %ErrorLevel% is non-zero.
Another frequent culprit is the use of variables within the command line before they are expanded. If you define a variable and then use it in a conditional block without enabling delayed expansion, the variable may hold its old value. While this usually affects text comparison, it can lead to confusing control flow if combined with external tools. Additionally, some third-party executables do not adhere to the standard exit code conventions. A program might return 0 even if it encountered a warning condition, or it might return a high number for informational purposes rather than fatal errors.
You can troubleshoot basic command execution issues, such as those involving directory listings which often fail silently, by referring to our article on Troubleshooting 'dir' Command Prompt Issues. Ensuring that your base commands are returning the expected codes is the first step in debugging chains.
Solving the Problem: Best Practices
To reliably handle error levels and prevent unwanted command execution, adopt the following practices. First, always check the immediate result of a command before proceeding. Use theif errorlevel N syntax carefully. Note that if errorlevel 1 is true for any error level greater than or equal to 1. If you need to check for a specific value like 99, you must use if %errorlevel% equ 99.
Second, consider using call :subroutine structures to isolate error handling. This allows you to jump to a specific label if a command fails, bypassing the rest of the script cleanly. Third, enable delayed variable expansion using setlocal enabledelayedexpansion if you are modifying variables inside loops or conditional blocks. This ensures that the most current value of %ErrorLevel% or other variables is used during evaluation.
Finally, log your exit codes. Adding echo [ERROR] Code: %ErrorLevel% after critical commands provides visibility into what is happening. This diagnostic step helps distinguish between a logic error in your script and an unexpected return value from an external tool. By strictly separating the execution flow from the error reporting, you can build robust batch files that respect the integrity of %ErrorLevel%.
Frequently Asked Questions
Does the && operator work with PowerShell?
No, the&& operator is specific to the Command Prompt (cmd.exe) and batch files. PowerShell uses semicolons (;) to separate commands sequentially and & for the call operator. To achieve similar logic in PowerShell, you should use if (-not $?) { ... } or throw exceptions that halt execution. Mixing these syntaxes in a mixed environment can lead to unexpected results.
How do I check if an error level is exactly 99?
You cannot useif errorlevel 99 because it matches any value greater than or equal to 99. Instead, use the equality operator: if %errorlevel% equ 99. This ensures that only the specific exit code of 99 triggers the subsequent action. Always wrap %errorlevel% in quotes if there is any chance it contains non-numeric characters, though this is rare for standard executables.
Why is my batch file ignoring the error level after a call?
When you use thecall command to run another batch file, the child script overwrites %ErrorLevel% with its own final exit code. To preserve the original error level, save it to a temporary variable immediately after the call: set prevError=%errorlevel%. Then, restore it or check the saved variable. This prevents the parent script from losing track of where the failure originated.
Can I use && with built-in commands like echo?
Yes, but be cautious. Built-in commands likeecho typically return 0 (success). However, if echo encounters a syntax error or an invalid redirect, it may return a non-zero code. In most cases, chaining echo with && is safe because echo rarely fails. However, relying on it for critical logic is risky compared to using external executables with defined exit codes.
What happens if I use || instead of &&?
The|| (OR) operator runs the next command only if the previous command failed (returned a non-zero exit code). If you accidentally use || when you intended to use &&, your script will execute cleanup or error-handling commands when things go wrong, rather than when they succeed. This is a common source of confusion for beginners transitioning from other programming languages.