‘||’ (logical OR) - DOS/Command Prompt Reference
[Windows NT series] Executes the right side command only when the left side command fails.
Syntax
<command1> || <command2>
Details
Strictly speaking, if only the exit code (Errorlevel) of the command line on the left of ‘||’ is not 0, the command line on the right will be executed. If the exit code of the left is 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 non-zero (true), 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 0 is treated as ‘true’, resulting ‘do not execute the right side when 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,
hoge.exe || echo %ERRORLEVEL%
... 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 hoge.exe || echo !ERRORLEVEL!
... the exit code of ‘hoge.exe’ can be used correctly.
If <command1> or <command2> includes ‘||’ or ‘&&’, and you want to change condition evaluation order, enclose corresponding command lines with parentheses ‘( )’. The following is an example.
(program1.exe || program2.exe) && (program3.exe || program4.exe || program5.exe)
This example behaves as follows:
- First, ‘program1.exe’ is executed, and if successful, ‘program2.exe’ is ignored and the command line including ‘program3.exe’ is executed.
- If ‘program1.exe’ fails, ‘program2.exe’ is executed, and if successful, the command line including ‘program3.exe’ is executed.
- If both ‘program1.exe’ and ‘program2.exe’ fail, the command line including ‘program3.exe’ is not executed.
- In the command line including ‘program3.exe’, if ‘program3.exe’ succeeds, the process finishes, and if it fails, ‘program4.exe’ is executed, and also if ‘program4.exe’ fails, ‘program5.exe’ is executed.
* If ‘program3.exe || program4.exe || program5.exe’ is not enclosed with parentheses, it will be same as ‘((program1.exe || program2.exe) && program3.exe) || program4.exe || program5.exe’.
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 much different from ‘||’.