Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment problem in DOS batch file for loop

Tags:

batch-file

dos

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

like image 674
RameshVel Avatar asked Dec 22 '22 23:12

RameshVel


1 Answers

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.

like image 156
Michael Madsen Avatar answered Jan 24 '23 10:01

Michael Madsen