How does && work within a batch/cmd script?

(I am using Win10 20H2)
I know if you have command A && command B, then command B only executes if command A was "completed successfully", but how exactly is it decided whether command A was successful or not?

  • My first thought was that it must be based on errorlevel's, but that can't be it as the following shows if you press enter without entering an input, then, as expected, you will not see a "success" message and the errorlevel is changed to 1:
    @echo off
    :loop
    set /p u_p= && echo success
    echo current errorlevel %errorlevel%
    goto loop
    
    However, if you subsequently enter valid inputs, you get a success message despite the errorlevel remaining at 1, so what is triggering the && to give the success message?

  • It has been suggested delayed expansion might be needed, as without it the code is false reporting the current errorlevel, however I've tried that, along with replacing the line referencing the errorlevel, but I still get the outputs to indicate success despite the errorlevel not being 0 for all subsequent inputs after entering an empty input:
    if errorlevel 1 (echo current errorlevel geq 1) else (echo current errorlevel leq 0)
    

I am reasonably certain the explanation is not && is being triggered by a 0 errorlevel, but that the code is causing a false reporting of the errorlevel?


Solution 1:

My first thought was that it must be based on errorlevels.

It is, but you are missing enabledelayedexpansion.

This is required because there is effectively a loop in your script and without enabledelayedexpansion the errorlevel variable is set the first time through and then doesn't change.

Using setlocal enabledelayedexpansion will give the behaviour you are expecting:

@echo off
setlocal enabledelayedexpansion
:loop
set /p u_p= && echo success
echo current errorlevel %errorlevel%
goto loop
endlocal

EnableDelayedExpansion

Setting EnabledDelayedExpansion will cause each variable to be expanded at execution time rather than at parse time.

Source Setlocal - Local variables - Windows CMD - SS64.com


Further Reading

  • An A-Z Index of the Windows CMD command line | SS64.com
  • Windows CMD Commands (categorized) - Windows CMD - SS64.com