关于 !var! 变量在符合语句中如何 ‘续命’ 给 %var% 变量,是批处的一个经典话题,已知 endlocal &set "gv=%lv%" 或 endlocal &set "gv=%%lv%%" 两个句式可用于非复合语块,但在复合语块中则无效(因cmd预处理所致),这就是为何一楼代码27行赋值无效而导致 if 分支错判的关键原因...
要在复合语块中实现!v! ‘续命’ 给%v%,可参考以下代码示例(关键是逃逸cmd预处理)
一。一个变量 !_#xx! ‘续命’ 给变量 %_#xx%- @echo off &setlocal &set/a "_#xx=0"
- for /l %%n in (1,1,3) do (
- setlocal enabledelayedexpansion
- set/a "_#xx+=1, xx+=1"
- for /f "delims=" %%a in ('set _#') do (endlocal&set "%%a")
- )
- set _#
- echo,xx=%xx%
- pause&exit/b
复制代码
二。多个!v! 变量 !_#xx!, !_#yy!, !_#zz! ‘续命’ 给变量 %_#xx%, %_#yy%, %_#zz%- @echo off &setlocal &set/a "_#xx=_#yy=_#zz=0"
- for /l %%n in (1,1,3) do (
- setlocal enabledelayedexpansion
- set/a "_#xx+=1, _#yy+=5, _#zz+=10, xyz+=1"
- set "k=1" &for /f "delims=" %%a in ('set _#') do (
- if defined k (endlocal&set "k=")
- set "%%a")
- )
- set _#
- echo,xyz=%xyz%
- pause&exit/b
复制代码