如果我像这样运行这个批处理文件,它会在IF循环中失败。如果我删除IF循环(和结束")"它按预期工作。 (t永远不会设置为您输入的内容)。
IF 1==1 (
set /p t=type in value
echo You typed: %t%
set t=%t% plus Suffix
echo Your value + suffix: %t%
)
pause
答案 0 :(得分:1)
您需要setlocal enabledelayedexpansion
@echo off
setlocal enabledelayedexpansion
IF 1==1 (
set /p "t=type in value: "
echo You typed: !t!
set "t=!t! plus Suffix"
echo Your value + suffix: !t!
)
pause
endlocal
exit/B
当命令处理器找到一个块(括号之间的任何内容)时,完全解析它并将变量扩展到它们在计算块时所具有的值。如果更新块中的变量值,则需要为变量启用延迟扩展以反映所做的更改。您还必须将%var%
更改为!var!
考虑以下
@echo off
setlocal enabledelayedexpansion
set "var=Round 0"
echo( ----------------------------------------------
for /L %%i in (1,1,5) do (
set "var=Round %%i"
echo( var is %var% [not using delayed expansion]
echo( var is !var! [using delayed expansion]
echo( ----------------------------------------------
)
echo( After block %var% !var! are the same
pause
exit/B