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

Categories

@echo off
SET first=0
FOR %%N IN (hello bye) DO (
SET first=1
echo %first%
echo %%N
)

It seems that the variable "first" is always 0. Why?

See Question&Answers more detail:os

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

1 Answer

With batch files, variables are expanded when their command is read - so that would be as soon as the for executes. At that point, it no longer says echo %first%, it literally says echo 0, because that was the value at the point of expansion.

To get around that, you need to use delayed expansion by surrounding your variable name with ! instead of % - so that would be echo !first!. This may require you to start cmd.exe with the /V parameter, or use setlocal enabledelayedexpansion in the beginning of your batch file (just after echo off).

If you type set /?, you'll see a much more detailed explanation of this at the end of the output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...