Batch File Set Variable not working

80,311

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%
Share:
80,311

Related videos on Youtube

Richard Schaefer
Author by

Richard Schaefer

Started in IT in 1974 with a NASA STIF on my campus as a PL/1 developer and operations specialist while still in college. 22 years with a major New England bank until it was sold, three years as a consultant, three years with Connecticut State University System as Director of Technical Services, 15+ years with The Hartford in various positions. Now a Sr. IT Engineer in the DevOps practice. We support a fully automated CI/CD system where I focus on automation of build/deploy for Microsoft-based applications. Just learning PowerShell to replace older BAT files and VBScript code in our automation workflows.

Updated on January 06, 2020

Comments

  • Richard Schaefer
    Richard Schaefer almost 3 years

    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?

    • jeb
      jeb about 9 years
      No one said, that you should put spaces between Testvar and the equal sign.
    • mavrosxristoforos
      mavrosxristoforos about 9 years
      Not sure about this, but maybe you need to EnableDelayedExpansion
    • Richard Schaefer
      Richard Schaefer about 9 years
      Spaces around the equal signs <sigh>... I knew it was something really dumb. Thanks.
    • Kathy Lori
      Kathy Lori over 3 years
      I just did the same darn thing. How dumb.