The command for
can be used to enumerate a directory and apply (a) certain command(s) on each item. With the /R
the same can be accomplished for a full directory tree.
What happens when the content of the enumerated directory (tree) is changed by the command(s) in the body of the for
command?
Supposed we have the directory D:data
with the following content:
file1.txt
file2.txt
file3.txt
The output of for %F in ("*.txt") do echo %F
when executed in said directory will reflect the above list obviously.
However, what is the output of the for
loop when a command in the for
body modifies the content of the directory? For instance, one of the files in the list is deleted, let's say file3.txt
, before it is actually iterated? Or if a new file is created, like file4.txt
, before completion of the loop?
How does for /R
behave in that context? Supposed there are several sub-directories sub1
, sub2
, sub3
, each containing the above list of files; for /R
is currently iterating through sub2
, sub1
has already been processed, but sub3
not yet; the contents of sub1
and sub3
are changed at that point (when currently walking through sub2
as mentioned); what will be enumerated then? I guess, the change of the content of sub1
won't be recognised, but what about sub3
?
Finally, is there a difference in behaviour of for
or for /R
when being executed in the command prompt or from a batch file? And are there differences in different Windows versions?
Note:
See also my similar question about the forfiles
command.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…