6

I am learning Batch scripting and I copied example how to check for empty :

@echo off 
SET a= 
SET b=Hello 
if [%a%]==[] echo "String A is empty" 
if [%b%]==[] echo "String B is empty "

but I get such error:

D:\Projects\Temp\BatchLearning>Script.bat
]==[] was unexpected at this time.

what the problem? Why this was in guide. Did it work in past? Example from here.

UPD:

I deleted some whitespaces in the end of 2nd, 3rd and 5th(last) lines and everything works now as expected, what is going on?

Community
  • 1
  • 1
Borys Fursov
  • 548
  • 2
  • 5
  • 15
  • 1
    `if "%a%"==""`, or even better, `if not defined a` – aschipfl Aug 28 '18 at 15:03
  • @aschipfl But why did that spaces destroyed my script? – Borys Fursov Aug 28 '18 at 15:04
  • The space is a token separator in CMD, which must be protected by surrounding `""`... – aschipfl Aug 28 '18 at 15:05
  • You should use the extended syntax of SET `set "a="` and `set "b=Hello"` to avoid trailing invisible spaces.See also the answer of Mofi. `set "="` the quotes are not stored in the variable, but the last quote is the end mark for the content – jeb Aug 28 '18 at 15:15

1 Answers1

7

An environment variable cannot have an empty string. The environment variable is not defined at all on assigning nothing to an environment variable.

The help of command IF output on running in a command prompt window explains the syntax:

if defined Variable ...
if not defined Variable ...

This works as long as command extensions are enabled as by default on starting cmd.exe or running a batch file.

@echo off
SET "a="
SET "b=Hello"
if not defined a echo String A is empty.
if not defined b echo String B is empty.

The square brackets have no meaning for command IF or for Windows command processor. But double quotes have one as they define an argument string. So possible is also using:

@echo off
SET "a="
SET "b=Hello"
if "%a%" == "" echo String A is empty.
if "%b%" == "" echo String B is empty.

But please note that a double quote character " inside string value of a or b with expansion by command processor before execution of the parsed command line as done here with %a% and %b% results in a syntax error of the command line.

Read also answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? why it is recommended to use the syntax set "Variable=Value" to avoid getting assigned to an environment variable a value with not displayed trailing whitespaces.

Mofi
  • 46,139
  • 17
  • 80
  • 143