Reputation: 579
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?
Upvotes: 6
Views: 13540
Reputation: 49086
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.
Upvotes: 7