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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With