Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

batch file - Use a variable in a 'for' loop

I have following code:

@echo off
SET ITER=0
for %%i in (%*) do (
  SET ITER+=1
  ECHO %ITER%
)

The output is (for three arguments):

0
0
0

Expected output:

1
2
3

Why can't I access the updated variable in the for loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Expansion of variables with percents is done before a statement/block is executed.
So in your case the complete block is expanded before the echo %ITER% is executed, to constant echo 0.
The variable ITER itself is updated in the loop properly.

To avoid this, you could use the delayed expansion, this works like percent expansion but just in the moment of execution

@echo off
setlocal EnableDelayedExpansion
SET ITER=0
for %%i in (%*) do (
  SET /a ITER+=1
  ECHO !ITER!
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...