Variable assignment problem in DOS batch file for loop

13,398

You need to use delayed expansion - !Word1! instead of %Word1%.

By default, when the shell first reads the statement, all variables are substituted with their current values, and the modified statement is used every time that line is hit. This is simply how DOS works, and it's kept that way in the Windows shell for backwards compatibility.

Delayed expansion, on the other hand, reinserts the value every time the statement is hit. That will give you the desired result.

Share:
13,398
RameshVel
Author by

RameshVel

தொட்டு விடும் தூரத்தில் வெற்றியும் இல்லை விட்டு விடும் எண்ணத்தில் நானும் இல்லை - ரமேஷ் வேல் building https://dailybasket.com/?utm_source=stackoverflow&utm_medium=stackoverflow&utm_campaign=stackoverflow_bio

Updated on August 08, 2022

Comments

  • RameshVel
    RameshVel over 1 year

    I have a variable assignment problem inside the DOS script for loop. It never assigns the value, its always blank. Below the sample code

    @echo off
    set ans=%1
    SET STRING=%ans:"=%
    
    echo Parsing the string "%STRING%":
    for /f "tokens=1-2" %%a in ("%STRING%") do (
     set Word1 =%%a
     echo Word 1: %%a
     echo Word 1: %Word1%
     set Word2 =%%b
     if %%b.==. (Set server =\\.\pipe\mssql$microsoft##ssee\sql\query ) else (Set server =%%b)
    )
    echo Server name "%server%"
    sqlcmd -s %server%
    

    value of %%a is not assigned to variable Word1. But when i echo the %%a, it shows the correct value. As well in the last empty value check if condition, the server variable never set. I am very confused here. can someone help me out??

    P.S: input to the script is any 2 word string (ex: a.bat "l dev-server")