2

Why is this string not concatenating?

@echo off
set NUM_NODES=4
set ENSEMBLE=127.0.0.1:2181

for /l %%x in (2, 1, %NUM_NODES%) do (
    echo %%x
   set ENSEMBLE=%ENSEMBLE%,127.0.0.1:2%%x81
)
echo ensemble: %ENSEMBLES%

OUTPUT:

2
3
4
ensemble: 127.0.0.1:2181,127.0.0.1:2481

2 Answers 2

5

Because in batch files variables are expanded when a command is parsed, not immediately prior to its execution. If you want the latter behaviour, you need to use delayed expansion:

setlocal enabledelayedexpansion
@echo off
set NUM_NODES=4
set ENSEMBLE=127.0.0.1:2181

for /l %%x in (2, 1, %NUM_NODES%) do (
    echo %%x
   set ENSEMBLE=!ENSEMBLE!,127.0.0.1:2%%x81
)
echo ensemble: %ENSEMBLES%

help set contains a lengthy description and exactly your example.

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

Comments

0

Both the original example and the answer contain the same typo, adding an S to the end of the variable in the ECHO statement, so neither example as it appears produces any output from the variable.

Comments

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.