Stainedart
Stainedart

Reputation: 1969

Batch file string concatenation

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

Upvotes: 2

Views: 3860

Answers (2)

Matt
Matt

Reputation: 1

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.

Upvotes: 0

Joey
Joey

Reputation: 354476

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.

Upvotes: 5

Related Questions