12

I've seen cmd batch scripts using square notation to surround a variable. For example:

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

What is the purpose of this?

2 Answers 2

17

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

4
  • So quotes "" and [] can be used interchangeably for the purposes of empty varaibles? There's no difference? I thought maybe there is some advantage of using [] compared to ""
    – Jim
    Commented May 8, 2014 at 21:48
  • 8
    @Jim - There is no advantage to using [%var%]==[value]. It would work just as well as ]%var%[==]value[ or XXX%var%==XXXvalue. There is an advantage to using "%var%"=="value" because it will not fail if var contains an unquoted poison character like &.
    – dbenham
    Commented May 9, 2014 at 4:23
  • 1
    @dbenham - however, it will fail if var contains an unquoted poison character like ". Consider SET var="foo bar", which becomes if ""foo bar""==""; which will likely award you a bar""=="" was unexpected at this time.... Commented Aug 24, 2017 at 18:42
  • 1
    @jimbobmcgee - Yes, that is why I always try to keep quotes out of my variable values. If I really want robust code that can handle any content, then I use delayed expansion.
    – dbenham
    Commented Aug 24, 2017 at 19:17
3

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.