Conditional Execution

Conditional Execution Based on Result of Previous Command.

Description: Command1 && SuccessCommand
Command1 || FailCommand
Command1 && SuccessCommand || FailCommand

The && operator can be used to execute a command only when the previews command succeeded.
The || operator can be used to execute a command only when the previews command failed.

Example 1
Show a message only when the string "ERROR" exist in the logfile.log file. The find command succeeds when the string "ERROR" exist in logfile.log. The output of the find command is redirected into the NUL devise since we don`t want to see any of its output in the output window.

Example 2
Show a message only when the string "ERROR" doesn`t exist in the logfile.log file. The find command fails when the string "ERROR" doesn`t exist in logfile.log. The output of the find command is redirected into the NUL devise since we don`t want to see any of its output in the output window.

Example 3
The Conditional Execution operators are useful with many DOS commands, i.e. the SET command.

Note
Be careful when combining the operators, i.e.:
Command1 && (CommandBlock2) || (CommandBlock3)
  • If Command1 fails then CommandBlock2 will be skipped and CommandBlock3 will be executed.
  • If Command1 succeeds then CommandBlock2 will be executed.
  • If Command2 fails then CommandBlock3 will also be executed!!

To avoid this pitfall force CommandBlock2 to succeed, i.e. using a simple REM as last block command:
Command1 && (CommandBlock2 & REM) || (CommandBlock3)

or:
Command1 && (
    CommandBlock2
    REM force success
) || (
    CommandBlock3
)
Script: Download: BatchConditionalExecution.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
@ECHO OFF

echo.
echo.1:
echo.   ...finding 'ERROR' in logfile.log
find "ERROR" logfile.log>NUL && (
    echo.   yes, "ERROR" in logfile
)

echo.
echo.2:
echo.   ...finding 'ERROR' in logfile.log
find "ERROR" logfile.log>NUL || (
    echo.   no "ERROR" in logfile
)

echo.
echo.3:
set "v=old_value"
set /p "v=   ...enter a value or just hit ENTER: " && (
    echo.   The user entered a value, the variable v changed.
) || (
    echo.   The user just hit Enter, the variable v remains unchanged.
)
echo.   v is now: %v%
Script Output:
 DOS Script Output
1:
   ...finding 'ERROR' in logfile.log

2:
   ...finding 'ERROR' in logfile.log
   no "ERROR" in logfile

3:
   ...enter a value or just hit ENTER: 
   The user just hit Enter, the variable v remains unchanged.
   v is now: old_value