如何以安全的方式回显字符串%I
,而不管echo
命令行是否放在for %I
循环中?
例如,在命令提示符(cmd
)中:
>>> rem // `echo` is outside of `for` scope, so this works:
>>> echo %I
%I
>>> rem // `echo` is inside of `for` scope, so `%I` is resolved:
>>> for %I in (.) do @echo %I
.
>>> rem // escaping does not help, `%I` is still resolved:
>>> for %I in (.) do @(echo ^%I & echo %^I & echo ^%^I & echo %%I)
.
.
.
%.
在批处理文件中......:
@echo off & rem // Here you need to double the `%` signs!
rem // `echo` is outside of `for` scope, so this works:
echo %%I & echo %%%%I
echo/
rem // `echo` is inside of `for` scope, so `%%I` is resolved:
for %%I in (.) do (echo %%I & echo %%%%I)
echo/
rem // escaping does not help, `%%I` is still resolved:
for %%I in (.) do (echo ^%%I & echo %%^I & echo ^%%^I & echo ^%^%I & echo ^%^%^I & echo ^%%^%%^I)
......结果是:
%I %%I . %. . . . I ^I %.
那么我如何更改上述方法(cmd
和批处理文件)以使%I
回显?
答案 0 :(得分:3)
有两种方法可以解决for
引用%I
的意外扩展问题:
在cmd
:
>>> rem // Ensure that delayed expansion is enabled!
>>> set "STR=%I"
>>> echo !STR!
%I
>>> for %I in (.) do @echo !STR!
%I
在批处理文件中......:
@echo off & rem // Here you need to double the `%` signs!
setlocal EnableDelayedExpansion
set "STR=%%I"
echo !STR!
for %%I in (.) do echo !STR!
set "STR=%%%%I"
echo !STR!
for %%I in (.) do echo !STR!
endlocal
...结果:
%I %I %%I %%I
然而,在某些情况下,延迟扩张可能会造成伤害;环境本地化也可以由setlocal
/ endlocal
完成。
但还有另一种方式:
for
循环在cmd
:
>>> for %J in (%I) do @echo %J
%I
>>> for %J in (%I) do @for %I in (.) do @echo %J
%I
在批处理文件中......:
@echo off & rem // Here you need to double the `%` signs!
for %%J in (%%I) do (
echo %%J
for %%I in (.) do echo %%J
)
for %%J in (%%%%I) do (
echo %%J
for %%I in (.) do echo %%J
)
...结果:
%I %I %%I %%I
虽然你现在不能再回复%%J
了。
for
圈(根据dbenham' s suggestion编辑)在cmd
:
>>> for %J in (%) do @echo %JI
%I
>>> for %J in (%) do @for %I in (.) do @echo %JI
%I
在批处理文件中......:
@echo off & rem // Here you need to double the `%` signs!
for %%J in (%%) do (
echo %%JI
for %%I in (.) do echo %%JI
)
for %%J in (%%%%) do (
echo %%JI
for %%I in (.) do echo %%JI
)
...结果:
%I %I %%I %%I
这次甚至可以回复%%J
。