我有以下Windows批处理文件:
@echo off
set MYVAR1=test
set MYVAR2=
set MYVAR3=a b c
setlocal enableDelayedExpansion
for /l %%x in (1, 1, 3) do (
if !MYVAR%%x! == "" (
echo Not defined
) else (
echo Variable is: !MYVAR%%x!
)
)
我希望它能打印以下输出:
Variable is: test
Not defined
Variable is: a b c
相反,我看到以下输出:
Variable is: test
Variable is:
Variable is: a b c
这对我没有任何意义!如何更改批处理脚本以获得所需的输出?
答案 0 :(得分:1)
还需要将延迟表达式括在引号中。
if "!MYVAR%%x!" == "" (
而不是
if !MYVAR%%x! == "" (
所以示例代码现在看起来像:
@echo off
set MYVAR1=test
set MYVAR2=
set MYVAR3=a b c
setlocal enableDelayedExpansion
for /l %%x in (1, 1, 3) do (
if "!MYVAR%%x!" == "" (
echo Not defined
) else (
echo Variable is: !MYVAR%%x!
)
)
答案 1 :(得分:0)
现在更正的代码的替代方法是不测试空值,而是使用if defined
@echo off
set "MYVAR1=test"
set "MYVAR2="
set "MYVAR3=a b c"
setlocal enableDelayedExpansion
for /l %%x in (1, 1, 3) do if not defined MYVAR%%x (
echo Variable %%x Not defined
) else (
echo Variable %%x is: !MYVAR%%x!
)