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?

4
  • 1
    if "%a%"=="", or even better, if not defined a Commented Aug 28, 2018 at 15:03
  • @aschipfl But why did that spaces destroyed my script? Commented Aug 28, 2018 at 15:04
  • The space is a token separator in CMD, which must be protected by surrounding ""... Commented Aug 28, 2018 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 "<var>=<content>" the quotes are not stored in the variable, but the last quote is the end mark for the content Commented Aug 28, 2018 at 15:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.