Programming Field

‘&&’ (logical AND) - DOS/Command Prompt Reference

[Windows NT series] Executes the right side command only when the left side command succeeds.

Syntax

<command1> && <command2>

Details

Usage of ‘&&’

Strictly speaking, if only the exit code (Errorlevel) of the command line on the left of ‘&&’ is 0, the command line on the right will be executed. If the exit code of the left is not 0, the command line on the right will not be executed.

In C language or etc., when the evaluated value of the expression on the left side of ‘&&’ is zero (false), the expression on the right side will not be evaluated (short circuit). Command Prompt's ‘&&’ behaves almost identically to those, but for the exit codes ‘0’ usually means ‘successful’, so the exit code non-0 is treated as ‘false’, resulting ‘do not execute the right side when non-0’.

As a point of caution, if using environment variables in either or both command lines, the all environment variables will be expanded before all command execution (This behavior is same as using parentheses in If and For). Therefore,

call :piyo && echo %RETVAR%

... this command line causes unexpected result in almost all cases. To avoid this, in case Extensions are enabled, by using Setlocal and ‘!’ as follows:

setlocal enabledelayedexpansion
call :piyo && echo !RETVAR!

... the exit code of execution of label ‘piyo’ can be used correctly.

When using both ‘&&’ and ‘||’, the operation priority of ‘||’ is same as ‘&&’, resulting executing left to right. To change the order, use parentheses ‘( )’. (Please see ‘||’ for details.)

To include ‘&&’ characters themselves as part of the command line, or to print ‘&&’ by using Echo command or etc., enclose with ‘" "’ if they can be used, or otherwise put ‘^’ character just before each ‘&’ characters (i.e. ‘^&^&’).

Note that ‘&’ is different from ‘&&’.