Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square bracket notation around variable in cmd / DOS batch scripts

Tags:

batch-file

cmd

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?

like image 942
Jim Avatar asked May 08 '14 20:05

Jim


1 Answers

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

like image 100
Stephan Avatar answered Sep 21 '22 15:09

Stephan