批处理文件字符串连接

Sta*_*art 2 string batch-file

为什么这个字符串没有连接?

@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%
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

2
3
4
ensemble: 127.0.0.1:2181,127.0.0.1:2481
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 5

因为在批处理文件中,在解析命令时会扩展变量,而不是在执行之前立即扩展变量.如果您想要后一种行为,则需要使用延迟扩展:

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%
Run Code Online (Sandbox Code Playgroud)

help set 包含冗长的描述和确切的例子.