Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch File Set Variable not working [duplicate]

I'm doing some simple setting of a variable in a BAT file. It's not setting the variable. There aren't any odd constructs, it's simple variable substitution using the same variable name. I reduced the BAT file to a simple proof of concept version:

set TESTVAR = "No Value"
ECHO var = %TESTVAR%
set TESTVAR = ""
ECHO var = %TESTVAR%
set TESTVAR = "New value"
ECHO var = %TESTVAR%

And the output shows that none of the SET commands seem to be working. What the heck am I missing here. I've been writing BAT files for years and I've never seen this before. Here's the output from running this test:

C:\Users\rs02130\Desktop>test

C:\Users\rs02130\Desktop>set TESTVAR = "No Value"

C:\Users\rs02130\Desktop>ECHO var =
var =

C:\Users\rs02130\Desktop>set TESTVAR = ""

C:\Users\rs02130\Desktop>ECHO var =
var =

C:\Users\rs02130\Desktop>set TESTVAR = "New value"

C:\Users\rs02130\Desktop>ECHO var =
var =
C:\Users\rs02130\Desktop>

I expect the first and third ECHO commands to display the values "No Value" and "New value". What the heck is going on?

like image 565
Richard Schaefer Avatar asked Oct 18 '13 11:10

Richard Schaefer


People also ask

What does %% A mean in batch file?

%%a refers to the name of the variable your for loop will write to. Quoted from for /? : FOR %variable IN (set) DO command [command-parameters] %variable Specifies a single letter replaceable parameter. (set) Specifies a set of one or more files.

Can you use variables in batch files?

When creating batch files, you can use set to create variables, and then use them in the same way that you would use the numbered variables %0 through %9. You can also use the variables %0 through %9 as input for set. If you call a variable value from a batch file, enclose the value with percent signs (%).


1 Answers

The problem is the spaces around the equal sign. This should do what you want.

set TESTVAR="No Value" ECHO var = %TESTVAR% set TESTVAR="" ECHO var = %TESTVAR% set TESTVAR="New value" ECHO var = %TESTVAR% 
like image 139
THE JOATMON Avatar answered Sep 19 '22 01:09

THE JOATMON