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 ficheroTrue if the file or folder exists.
errorlevel NTrue if the last command's exit code is N or greater.
defined variableTrue if the environment variable is defined.
a==bTrue if the two texts are equal; they are usually put in quotes.
/iIgnores case differences in text comparisons.
notInverts the condition.
EQU NEQ LSS LEQ GTR GEQNumeric operators: equal, not equal, less, less or equal, greater and greater or equal.
elseCommand that runs if the condition is not met.
Usage examples
if exist notas.txt echo existePrints existe only if the file is in the folder.
if not exist backup mkdir backupCreates 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.