0

I have many strings set. There names are: User1 User2 User3 User4

And so on. They all are equal to random text. I want to display all of these Strings into the command line. This is one thing i've tried:

set /a N=1
:Loop
echo  %N% - %%User%N%N%%
set /a N+=1
goto Loop

The variable N starts at one, and each time :Loop is ran, it counts up. Im not worried about it going on forever right now, I just want it to display every String. Heres the output of what I tried:

1 - %User1N%
2 - %User2N%

It replaces %%Users%N%N%% with %User1N% when N = 1, which is almost what I want. But I want it to also replace %User1% with what that string is equal to. Some help would be appreciated.

Coding Mason
  • 162
  • 1
  • 14
  • 1
    Try `call echo %%User%N%%%`, see [batch script echo dynamic variable](https://stackoverflow.com/questions/51120907/batch-script-echo-dynamic-variable) why. – dxiv Jul 01 '20 at 00:48
  • 1
    The standard ways of doing this: **1-** `call echo %N% - %%User%N%%%` **2-** `echo %N% - !User%N%!` and the much simpler **3-** `for /L %%N in (1,1,4) do echo %%N - !User%%N!` are described with detail at [this answer](https://stackoverflow.com/a/10167990/778560). I suggest you to use the _standard array notation_ enclosing the _subscript_ between square braquets in this way: `echo %%N - !User[%%N]!` – Aacini Jul 01 '20 at 04:21

1 Answers1

2

In order to expand your variable twice you need to delay its expansion, and here are a couple of ways that can be achieved.

Using Call to effectively pass it through another cmd instance, (as mentioned in the comments):

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "User1N=Enrico"
Set "User2N=Francis"
Set "User3N=Helena"
Set "User4N=John"
Set "User5N=Roberto"

Set /A N=1

:Loop
Call Echo %N% - %%User%N%N%%
Set /A N+=1
If %N% Lss 6 GoTo Loop

"%__AppDir__%timeout.exe" /T 5 /NoBreak 1>NUL
EndLocal
GoTo :EOF

Using SetLocal to delay the epansion, (more efficient):

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "User1N=Enrico"
Set "User2N=Francis"
Set "User3N=Helena"
Set "User4N=John"
Set "User5N=Roberto"

Set /A N=1

:Loop
SetLocal EnableDelayedExpansion
Echo %N% - !User%N%N!
EndLocal & Set /A N+=1
If %N% Lss 6 GoTo Loop

"%__AppDir__%timeout.exe" /T 5 /NoBreak 1>NUL
EndLocal
GoTo :EOF
Compo
  • 36,585
  • 5
  • 27
  • 39