if

Windows CMD · Terminal · reference only

What it does

Runs a command only if a condition is met: if a file exists, if two texts are equal, if the error code is greater than a value...

Syntax

if [not] condición orden [else orden]

Options and parameters

  • exist fichero

    True if the file or folder exists.

  • errorlevel N

    True if the last command's exit code is N or greater.

  • defined variable

    True if the environment variable is defined.

  • a==b

    True if the two texts are equal; they are usually put in quotes.

  • /i

    Ignores case differences in text comparisons.

  • not

    Inverts the condition.

  • EQU NEQ LSS LEQ GTR GEQ

    Numeric operators: equal, not equal, less, less or equal, greater and greater or equal.

  • else

    Command that runs if the condition is not met.

Usage examples

  • if exist notas.txt echo existe

    Prints existe only if the file is in the folder.

  • if not exist backup mkdir backup

    Creates the backup folder only if it does not exist.

  • if /i "%OPCION%"=="s" (echo Sí) else (echo No)

    Compares ignoring case and chooses between two answers.

  • if errorlevel 1 echo La orden anterior falló

    Detects an error from the previous command.

Notes and common mistakes

  • else must be on the same line as the closing parenthesis of the previous command.
  • Put variables in quotes so an empty value does not break the comparison.

Related commands