Skip to content

Conditionals

rbaltrusch edited this page Feb 15, 2021 · 7 revisions

Conditionals

If

Batch supports IF statements, with an optional ELSE clause, to handle conditional logic. The following example checks if the first input argument equals the string "help" and outputs the help section if it does:

if "%~1" == "help" (
    echo Welcome to the help section!
)

If-Else

The following example checks if a file exists and outputs it to the console if it exists, otherwise outputting an error message:

IF EXIST myfile.txt (
    type myfile.txt
) else (
    echo The file does not exist!
)

Note that parentheses are required when the if-clause is followed by an else-clause.

Parentheses

As with the for loop, if the if-statement only contains a single statement and is not followed by an else clause, the parentheses may be omitted (although this should be avoided). The example below prints out the string success! to the console if the ERRORLEVEL is greater or equal to 1:

if ERRORLEVEL 1 echo success!

Operators

The following logical operators are available in Batch:

  • EQU (equal)
  • == (same as EQU)
  • NEQ (not equal to)
  • LSS (less than)
  • GTR (greater than)
  • LEQ (less than or equal)
  • GEQ (greater than or equal)

Conditional statements can be negated with an initial NOT, as in the following example, in which we output a warning to the console if the ERRORLEVEL variable is not equal to 0:

if not "%ERRORLEVEL%" == "0" (
    echo A problem might have occured!
)
Clone this wiki locally