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?

IslandPatrol
  • 261
  • 3
  • 11
  • 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." – rojo Dec 12 '16 at 18:57
  • That code does not output a **4** five times. It will output `ECHO IS OFF` five times. – Squashman Dec 12 '16 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. – IslandPatrol Dec 12 '16 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). – SomethingDark Dec 12 '16 at 19:39
  • 1
    Possible duplicate of [Windows Batch Variables Won't Set](http://stackoverflow.com/questions/9681863/windows-batch-variables-wont-set) – SomethingDark Dec 12 '16 at 19:39

1 Answers1

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.

Magoo
  • 77,302
  • 8
  • 62
  • 84