IF - CMD


Overview

The IF command in Windows Command Prompt (CMD) is used for conditional processing in batch scripts. It allows for the execution of commands based on specified conditions. This utility is instrumental in making logical decisions within scripts, thereby facilitating complex workflows and automated tasks.

Syntax

The IF command has various forms depending on the condition type:

  1. Equality Check:

    IF [NOT] condition command
    
    • NOT – Optional. Inverts the condition.
  2. Existential Check:

    IF [NOT] EXIST filename command
    
  3. String Comparison:

    IF [NOT] "string1"== "string2" command
    
  4. Errorlevel Check:

    IF [NOT] ERRORLEVEL number command
    
  5. Command Chaining:

    IF condition (command1) ELSE (command2)
    

Options/Flags

  • NOT: Reverses the condition, executing the command if the condition is false.
  • EXIST: Checks for the existence of a file or directory.
  • ERRORLEVEL: Checks if the last command’s error level is equal to or greater than a specified number.
  • ELSE: Allows for the execution of an alternative command if the initial condition is false.

Examples

  1. Checking file existence:

    IF EXIST myfile.txt (ECHO myfile.txt exists) ELSE (ECHO myfile.txt does not exist)
    
  2. Performing string comparison:

    IF "apple"=="banana" (ECHO Fruits are same) ELSE (ECHO Fruits are different)
    
  3. Using ERRORLEVEL:

    IF ERRORLEVEL 1 ECHO An error occurred with the last command
    
  4. Combined conditions:

    IF EXIST file1.txt (IF EXIST file2.txt (ECHO Both files exist))
    

Common Issues

  • Syntax Errors: Often occur due to missing quotes around strings or incorrect command structures. Ensure all expressions are enclosed correctly.
  • Case Sensitivity: The IF command is case-insensitive for string comparisons, which might lead to unexpected results if not accounted for.
  • Errorlevel Misunderstandings: ERRORLEVEL checks for values that are equal to or greater than the specified number, not just equal.

Integration

Combine IF with other commands to create comprehensive scripts:

IF EXIST config.sys (
    SET /P userinput=Enter your choice: 
    IF "%userinput%"=="Y" (
        DEL config.sys
    )
)

This script checks for a file, prompts the user for input, and deletes the file if the user confirms.

  • SET: Often used with IF for setting and using variables within conditional structures.
  • GOTO: Used in scripts to jump to other sections based on conditions.
  • FOR: Loops through items, often used with IF to handle each item conditionally.

For further reading and more complex examples, the official Microsoft documentation is a recommended resource: