views:

96

answers:

1

Hi,

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")

Cheers

+1  A: 

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.

Michael Madsen
@Michael, thanks for helping me out.. can you pls dummy edit your answer, then i can upvote it.. i have mistakenly removed the earlier upvote :(
Ramesh Vel
Sure thing. Here you go.
Michael Madsen