问题描述
我有DOS脚本循环中一个变量赋值问题。它从来没有分配值,它总是空白。下面的示例code
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%
%% a的值不赋给变量字1 即可。但是,当我呼应%%一个,它显示正确的值。以及在最后一个空值检查,如果条件下,服务器变量从未设置。我很困惑在这里。有人可以帮我?
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:输入脚本的2个字字符串(如:a.batL DEV-服务器)
P.S: input to the script is any 2 word string (ex: a.bat "l dev-server")
推荐答案
您需要使用延迟扩展! - 字1
而不是%字1 %
。
You need to use delayed expansion - !Word1!
instead of %Word1%
.
在默认情况下,当shell首先读的声明,所有变量取代它们的当前值,以及修改后的语句用于每个行被击中的时间。这是一个简单的DOS是如何工作的,以及它保持这种Windows外壳向后兼容。
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.
这篇关于在循环DOS批处理文件变量分配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!