Variable assignment issue in DOS batch file for loop

I have a problem with a variable variable inside a DOS script loop. It never assigns a value; it is always empty. Below is 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% 

%% a is not assigned to Word1 . But when I repeat the value of %% a, it shows the correct value. Also, in the last null value, check if the value of the server variable is defined. I am very confused here. can someone help me?

PS: the script entry is any 2-word string (for example: a.bat "l dev-server")

+4
source share
1 answer

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

By default, when the shell first reads the statement, all variables are replaced with their current values, and a modified statement is used every time this line hits. This is just how DOS works, and it has remained in the Windows shell for backward compatibility.

A deferred extension, on the other hand, re-enters a value each time an operator hits. This will give you the desired result.

+11
source

All Articles