zs2020
zs2020

Reputation: 54541

Problem of empty variable using set in Windows Batch

set var=%1
echo var
set command=""
IF var==true ( 
    set command=dir
)

IF var==false ( 
    set command=dir /a
)
echo %command%
%command%

So, if I run this script by typing in

C:\>test true

the echo %command% always prints "". Any idea?

Upvotes: 9

Views: 46343

Answers (2)

childno͡.de
childno͡.de

Reputation: 4824

I digged out that variable is empty if you are using conditions and set in conditions!

if errorlevel 0 (
   Set localVar="fooBar"
   echo "%localVar%"
)

will result in an empty output!

related to string comparison in batch file use

SetLocal EnableDelayedExpansion

to enable !VARNAME! that will enable to use !VARNAME! in a condition beneath but will still not enable output for %VARNAME% in the conditional block!

Use Set BEFORE the condition to get it accessible in the conditional block. OR usage must be AFTER conditional block where Set was used in.

(!) Currently I don't know how to challenge Set AND usage in the same block!

See some example code in https://gist.github.com/childnode/0f6c874ad79788a86332

(!) But as you can see in the results (also in gist) using DelayedExpansion has a different side effect:

Variable is set on second run in same shell (what is obviously correct) but for some reasons are not set with EnableDelayedExpansion in second run (seems to it also cleans up "local" variables from script and doesn't export it for following commands! This might cause other error if different batch files are run in "pipe"

Upvotes: 7

Frank Bollack
Frank Bollack

Reputation: 25196

You are missing some % signs that are needed for any variable dereferencing.

You probably want it like this:

set var=%1
echo %var%
set command=""
IF %var%==true (                    <=== here
    set command=dir
)

IF %var%==false (                   <=== here
    set command=dir /a
)
echo %command%
%command%

You should also surround your string comparisons with quotes to allow for spaces, something like this:

IF "%var%"=="false"

Also, as Joey pointed out, clearing a variable is done by

set command=

without any quotes. Otherwise you will initialize the the variable with these quotes, leading to your weird output.

Upvotes: 15

Related Questions