如何安全地回复文字字符串"%I"?

时间:2016-12-28 15:40:16

标签: windows batch-file for-loop cmd

如何以安全的方式回显字符串%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回显?

1 个答案:

答案 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