Windows“ for循环”中未分配变量

时间:2019-02-09 21:09:52

标签: windows batch-file for-loop

正在尝试制定一个“ for循环”,其中文件的内容被依次分配给环境变量。所以我有一个包含3条记录的文本文件:

edstest
roydev
uc4dev

然后我有此命令文件:

cls
@echo here is the contents of dblist.txt
type dblist.txt
for /f "tokens=*" %%x in (dblist.txt) DO (
  set  ORACLE_SID=%%x
  echo ORACLE_SID is %ORACLE_SID%
  pause
)

哪个产生此输出。请注意,“ set”命令似乎正在按计划进行文件输入,但是当我尝试通过回显已设置的变量的值进行验证时,我什么也没得到。同样有趣的是,如果我在同一会话中再次执行脚本,则在循环的每次迭代中,'echo ORACLE_SID为%ORACLE_SID%都会给出上一次执行时设置的最后一个值。

here is the contents of dblist.txt

C:\temp>type dblist.txt
edstest
roydev
uc4dev

C:\temp>for /F "tokens=*" %x in (dblist.txt) DO (
set  ORACLE_SID=%x
 echo ORACLE_SID is
 pause
)

C:\temp>(
set  ORACLE_SID=edstest
 echo ORACLE_SID is
 pause
)
ORACLE_SID is
Press any key to continue . . .

C:\temp>(
set  ORACLE_SID=roydev
 echo ORACLE_SID is
 pause
)
ORACLE_SID is
Press any key to continue . . .

C:\temp>(
set  ORACLE_SID=uc4dev
 echo ORACLE_SID is
 pause
)
ORACLE_SID is
Press any key to continue . . .

C:\temp>

我也用'setlocal EnableDelayedExpansion'尝试过,但这似乎没有效果:

修改后的脚本:

@echo on
cls
setlocal EnableDelayedExpansion
@echo here is the contents of dblist.txt
type dblist.txt
for /f "tokens=*" %%x in (dblist.txt) DO (
  set  ORACLE_SID=%%x
  echo ORACLE_SID is %ORACLE_SID%
  pause
)

结果:

C:\temp>setlocal EnableDelayedExpansion
here is the contents of dblist.txt

C:\temp>type dblist.txt
edstest
roydev
uc4dev

C:\temp>for /F "tokens=*" %x in (dblist.txt) DO (
set  ORACLE_SID=%x
 echo ORACLE_SID is
 pause
)

C:\temp>(
set  ORACLE_SID=edstest
 echo ORACLE_SID is
 pause
)
ORACLE_SID is
Press any key to continue . . .

C:\temp>(
set  ORACLE_SID=roydev
 echo ORACLE_SID is
 pause
)
ORACLE_SID is
Press any key to continue . . .

C:\temp>(
set  ORACLE_SID=uc4dev
 echo ORACLE_SID is
 pause
)
ORACLE_SID is
Press any key to continue . . .

C:\temp>

0 个答案:

没有答案