Strange question about windows batch file

2019-04-13 01:41发布

I got 1.txt and 2.txt in my working directory. I use the following batch to list all the files.

The batch is this:

@echo off
for /f "tokens=*" %%a in ('dir *.txt /b') do (
    echo ---------------
    set file_variable=%%a
    echo file_variable=%file_variable%
    echo filename=%%a
    )    

The result is below:

---------------
file_variable=2.txt   <---------------why it is not 1.txt here??
filename=1.txt
---------------
file_variable=2.txt
filename=2.txt

Thanks.

2条回答
Anthone
2楼-- · 2019-04-13 02:12

You need to put:

@setlocal enableextensions enabledelayedexpansion

at the top of your file and

endlocal

at the end.

Then you need to use the delayed expansion substitution characters.

@setlocal enableextensions enabledelayedexpansion
@echo off
for /f "tokens=*" %%a in ('dir *.txt /b') do (
    echo ---------------
    set file_variable=%%a
    echo file_variable=!file_variable!
    echo filename=%%a
)
endlocal

C:\Documents and Settings\Pax\My Documents> qq.cmd
---------------
file_variable=1.txt
filename=1.txt
---------------
file_variable=2.txt
filename=2.txt

What you're seeing without delayed expansion is that the entire for loop is being evaluated before running. That includes the substitution, so that %file_variable% will be replaced with the value it held before the loop started. Using delayed expansion defers the evaluation until the actual line is executed.


There are all sorts of wonderful Windows scripting tricks over at Rob van der Woude's site, containing quite a lot of different ways of doing things under Windows with various tools.

查看更多
Bombasti
3楼-- · 2019-04-13 02:25

In this particular case you could get the correct output if you ECHOed file_variable like this:

CALL ECHO file_variable=%%file_variable%%

This approach is less flexible and probably less performant than the one described in @paxdiablo's answer. It's probably just a quick-and-dirty method of delaying the expansion of a variable without the need to enable the special syntax for that.

查看更多
登录 后发表回答