以下批处理文件使用传入参数来获取第一个路径。
代码:
echo A. we started at = %cd%
set current=%cd%
pushd ..
echo #1 pushed to = %cd%
set parent=%cd%
pushd ..
echo #2 pushed to = %cd%
set grandparent=%cd%
echo .
if %argC% NEQ 10 (
echo the if statement starts at = %cd%
pushd ..
echo if statement: #3 pushed to = %cd%
popd ..
echo if statement: #4 popped to = %cd%
popd ..
echo if statement: #5 popped to = %cd%
)
echo .
echo B. after the if statement we start back at: %cd%
popd ..
echo #6 popped to = %cd%
popd ..
echo #7 popped to = %cd%
结果:
A. we started at = C:\test\test-layer-2\files
#1 pushed to = C:\test\test-layer-2
#2 pushed to = C:\test
.
the if statement starts at = C:\test
if statement: #3 pushed to = C:\test
if statement: #4 popped to = C:\test
if statement: #5 popped to = C:\test
.
B. after the if statement we start back at: C:\test\test-layer-2
#6 popped to = C:\test\test-layer-2\files
#7 popped to = C:\test\test-layer-2\files
Press any key to continue . . .
问题: 为什么if语句没有正确反映%cd%? *删除#1或#2会影响#3,#4,#5中输出的路径。 *改变#3,#4,#5的路径只能在B行正确输出结果。
答案 0 :(得分:3)
当您在块内使用变量时(在(和)之间,您需要启用延迟扩展:
setlocal enabledelayedexpansion
set var=hello
if "a"=="a" (
set var=world
echo %var% !var!
)
与您的%cd%
答案 1 :(得分:0)
您需要在批处理文件的顶部使用SetLocal EnableDelayedExpansion
。
请记住,将变量更改为代码块,例如一个if
句,for
等
然后您需要使用!
个字符代替%
:
...
echo if statement: #5 popped to = !cd!
...