DOS批处理文件for循环中的变量赋值问题
我在 DOS 脚本 for 循环中遇到变量赋值问题。它从不分配值,它总是空白。下面的示例代码中
@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 的值未分配给变量 Word1。但是当我回显 %%a 时,它显示了正确的值。同样在最后一个空值检查 if 条件中,服务器变量从未设置。我在这里很困惑。有人可以帮我吗?
PS:脚本的输入是任意 2 个单词的字符串(例如:a.bat“l dev-server”)
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")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用延迟扩展 -
!Word1!
而不是%Word1%
。默认情况下,当 shell 第一次读取语句时,所有变量都将替换为其当前值,并且每次命中该行时都会使用修改后的语句。这就是 DOS 的工作方式,并且在 Windows shell 中也保持这种方式以实现向后兼容。
另一方面,延迟扩展会在每次命中语句时重新插入该值。这会给你想要的结果。
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.