1

我写了下面的脚本:

@echo off
setlocal EnableDelayedExpansion

REM Collect source filenames from C:\Files and load into C:\doc.txt
dir C:\sources\Sourcefiles /b /a-d > C:\sourcefilenames.txt

REM fetch count of source files and store into variable count
For /F  %%I in ('call C:\count.bat ') Do Set count=%%I

REM loop "count" number of times and echo temp.txt value
FOR /L %%A IN (1,1,%count%) DO (

REM call line.bat to fetch line 1,line 2 and so on of sourcefilenames.txt    for each loop
call line.bat %%A>C:\temp.txt

set /p var=<C:\temp.txt
echo var:%var%    ----------> returns previous run value
type C:\temp.txt  ----------. returns current value of temp.txt

)

基本上我想从上面的脚本中做的是:我正在从 temp.txt 的内容创建一个变量(var)(temp.txt 中的数据将在每次循环运行时发生变化)以用于多个循环。

但我面临的问题是: Echo var is:%var% command 返回我以前的运行值不是 temp.txt 当前内容。而命令“type C:\temp.txt”返回我 temp.txt 当前内容。(注意:如果我从其他脚本调用/创建了变量“var”,它会返回之前的值,否则返回 Null)

非常感谢您对上述问题的帮助/指导。谢谢

4

2 回答 2

0

When CMD.exe encounters a block of code in parentheses, it reads and parses the entire block before executing. This can cause unintuitive behavior. In this case, your echo var:%var% line is being parsed once at the beginning of the loop and never again.

The easiest fix for this is to change that line to

echo var:!var!

The !var! syntax is parsed every time through the loop. This works because you have enabledelayedexpansion set in your script.

Another workaround to this type of problem is to remove the parentheses and instead call out to a subroutine.

FOR /L %%A IN (1,1,%count%) DO call :loopLineBat %%A
... rest of script
exit /b

:loopLineBat
 >%temp%\temp.txt call line.bat %1

<%temp%\temp.txt set /p var=
echo var:%var%
type %temp%\temp.txt
exit /b

This loop does the same as above, but because it is not in a parenthesized block, all of the lines are parsed and executed in order.

于 2016-06-25T17:50:06.250 回答
0

我想变量保留在内存中,没有被重新读取。尝试限制变量的有效性。setlocal echo something..... endlocal 或 @echo off & setlocal

于 2016-06-25T17:07:23.250 回答