Brackets 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) ( command command )
IF EXIST C:\pagefile.sys ( ECHO pagefile found on C: drive)
If the command will fit on a single line, then the brackets 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 brackets 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 bracket context and cause errors. A GOTO will also break a For-Do Loop.
The interpretation of comments/Labels within a bracketed code block is different/complex, so you may wish to put all comments outside the brackets.
The CMD shell statement does not use any great intelligence when evaluating brackets, 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 brackets like (ECHO Some^(more^)Potatoes)
It is worth noting that although brackets are legal in NTFS pathnames, such brackets will be misinterpreted by the command processor.
Do not use brackets 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.
“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 SS64.com 1999-2013
Some rights reserved