3

I would like to print the following:

0
1
2
3
4

I have tried this:

ECHO OFF
FOR /L %%A in (1,1,5) DO (
    SET /a "B=%%A-1"
    ECHO %B%
)

However, this gives me:

4
4
4
4
4

How can I achieve the desired output while using both A and B in my code?

5
  • 2
    This is a delayed expansion problem. Too lazy to google it, but there are hundreds of questions like this on SO already. Why not just for /L %%A in (0,1,4)? If that's not practical, then you should setlocal enabledelayedexpansion and echo !B!. For more info, do help set in a cmd console, paying attention to the section beginning "Finally, support for delayed environment variable expansion has been added." Commented Dec 12, 2016 at 18:57
  • That code does not output a 4 five times. It will output ECHO IS OFF five times. Commented Dec 12, 2016 at 19:06
  • 1
    @Squashman It output ECHO IS OFF five times the first time I ran it, but ouput 4 five times the next time I ran it. Commented Dec 12, 2016 at 19:18
  • 1
    That's because you ran it a second time without closing the cmd prompt (on a related note, good on you for running the script from the command prompt instead of double-clicking it). Commented Dec 12, 2016 at 19:39
  • 1
    Possible duplicate of Windows Batch Variables Won't Set Commented Dec 12, 2016 at 19:39

1 Answer 1

8
ECHO OFF
setlocal
FOR /L %%A in (1,1,5) DO (
    SET /a "B=%%A-1"
    call ECHO %%B%%
)

Since you are not using setlocal, B will be set to the value from the previous run. %B% will be replaced by 4 since B was set to 4 by the previous run. the call echo trick uses a parsing quirk to retrieve the current (run-time) value of the variable.

Here's "the official" way:

ECHO OFF
setlocal enabledelayedexpansion
FOR /L %%A in (1,1,5) DO (
    SET /a "B=%%A-1"
    ECHO !B!
)

In delayedexpansion mode, !var! retrieves the value of var as it changes at run-time. This is not without its drawbacks, but you'd need to read up on delayedexpansion for a guide on that matter.

Sign up to request clarification or add additional context in comments.

1 Comment

batch is such a pain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.