Square bracket notation around variable in cmd / DOS batch scripts

it is used for proper syntax. Just imagine, you want to check, if a variable is empty:

if %var%== echo bla

obviously will fail. (wrong syntax)

Instead:

if "%var%"=="" echo bla

works fine.

Another "bad thing": you want to check a variable, but it may be empty:

if %var%==bla echo bla

works well, if %var% is not empty. But if it is empty, the line would be interpreted as:

if ==bla echo bla

obviously a syntax problem. But

if "%var%"=="bla" echo bla

would be interpreted as

if ""=="bla" echo bla

correct syntax.

Instead of " you can use other chars. Some like [%var%], some use ! or . Some people use only one char instead of surrounding the string like if %var%.==. The most common is surrounding with " (because it will not fail if var contains spaces or an unquoted poison character like &.) *), but that depends on personal gust.

*) Thanks to dbenham, this is a very important information


The square brackets are needed to check for blanks because if you use:

if %1==[] (
echo no parameter entered
) else (
echo param1 is %1
)

Without the square brackets surrounding the variable, it will say

( is unexpected at this time

and exit.

Tags:

Batch File

Cmd