Using parenthesis/brackets to group expressions

Parenthesis can be used to split commands across multiple lines. This can make code more readable. Variables will be evaluated for the code block just as if the command was a single line.


        command )


   IF EXIST C:\pagefile.sys (
        ECHO pagefile found on C: drive)

If the command will fit on a single line, then the parenthesis can be omitted e.g.

IF EXIST data.xls Echo The file was found.


IF EXIST data.xls (
   Echo The file was  found.

When using parenthesis the CMD shell will expand [read] all the variables at the beginning of the code block and use those values even if the variables value is changed within the code block. Turning on DelayedExpansion will force the shell to read variables at the start of every line.

Code blocks can be used to expand variables in places where they would not otherwise be accepted such as the "tokens" parameter of the FOR command:

@echo off
set tknz="tokens=1-2"
   for /f %tknz% %%A in ('echo') do (
 		echo %%B
 		echo %%A

A GOTO command inside a bracketed code block will break the parenthesis context and cause errors. A GOTO will also break a For-Do Loop.
The interpretation of comments/Labels within a code block is different/complex, so put all comments outside the parenthesis.

The CMD shell statement does not use any great intelligence when evaluating parenthesis, so for example the command below will fail:

IF EXIST MyFile.txt (ECHO Some(more)Potatoes)

This version will work:

IF EXIST MyFile.txt (ECHO Some[more]Potatoes)

You could also escape the extra parenthesis like (ECHO Some^(more^)Potatoes)

It is worth noting that although parenthesis are legal in NTFS pathnames, such parenthesis will be misinterpreted by the command processor.

Testing Numeric values

Do not use parenthesis or quotes if you are comparing numeric values with an IF command
IF (2) GEQ (15) echo "bigger"
IF "2" GEQ "15" echo "bigger"

Will perform a character comparison and will echo "bigger"
however the commands

IF 2 GEQ 15 echo "bigger"
IF (2 GEQ 15) echo "bigger"

Will perform a numeric comparison and return the correct result.

This behaviour is opposite to the SET /a command where quotes are required.

The maximum number of nested in brackets expressions is 256 (more will cause a buffer overrun.)

“Yes, we are the richest major nation. But because so much of our national income is concentrated in relatively few hands, large numbers of Americans are worse off economically than their counterparts in other advanced countries” - Paul Krugman


DelayedExpansion - Force the shell to read variables at the start of every line.
IF - conditional command

© Copyright 1999-2015
Some rights reserved