4

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

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Beware though, as explained in this page ss64.com/nt/setlocal.html, that delayed expansion is not enabled by default. To enable it, you need to add this line in your script : SETLOCAL EnableDelayedExpansion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.