每当Windows命令解释器cmd.exe
遇到以以下开头的命令块的开头(
并以匹配结束)
,在执行留给命令块的命令之前,对整个块进行预处理。这意味着所有环境变量都使用%variable%
在执行命令之前,语法将被引用的环境变量的当前值替换,该命令稍后将执行整个命令块。从命令提示符窗口中运行批处理文件时可以看到此行为,而无需@echo off
通常位于批处理文件的顶部。
这意味着在您的批处理文件中使用IF命令和命令块在条件成立时执行%CD%
被当前目录替换before命令IF被执行,所以也被执行before命令CD完全被执行。
有两种可能:
- 显式启用延迟环境变量扩展并使用 using 语法在命令块中引用环境变量
!variable!
or
- 不要使用命令块GOTO或子程序和CALL.
启用延迟环境变量扩展的解决方案1:
setlocal EnableDelayedExpansion
if "%arg1%" == "aaa" (
cd "%~dp0..\apps\app_sample\samples\sample_app\build\outputs\apk"
adb.exe install "!CD!\sample_app-debug.apk"
)
endlocal
解决方案 2 根本不使用命令块而是使用GOTO:
if "%arg1%" == "aaa" goto AAA
rem Other commands
goto :EOF
:AAA
cd "%~dp0..\apps\app_sample\samples\sample_app\build\outputs\apk"
adb.exe install "%CD%\sample_app-debug.apk"
goto :EOF
rem Or use a different GOTO to continue processing somewhere else in batch file.
另一个解决方案 2 是使用子例程和命令CALL:
if "%arg1%" == "aaa" call :AAA
rem Other commands executed even if above condition is true.
rem Avoid a fall through to the subroutine below.
goto :EOF
:AAA
cd "%~dp0..\apps\app_sample\samples\sample_app\build\outputs\apk"
adb.exe install "%CD%\sample_app-debug.apk"
rem Exit the subroutine and continue on line below calling it.
goto :EOF
但我认为您的代码可以更简单,因为很可能不需要指定带有完整路径的 *.apk 文件。
if "%arg1%" == "aaa" (
cd "%~dp0..\apps\app_sample\samples\sample_app\build\outputs\apk"
adb.exe install sample_app-debug.apk
)
也许也起作用的是:
if "%arg1%" == "aaa" adb.exe install "%~dp0..\apps\app_sample\samples\sample_app\build\outputs\apk\sample_app-debug.apk"
最好用在这里%~dp0
它引用以反斜杠结尾的批处理文件的驱动器和路径,而不是%~f0
这是带有文件扩展名和完整路径的批处理文件的名称。
例如批处理文件是C:\Temp\Test\Install.bat
命令行
cd "%~f0\..\..\apps\app_sample\samples\sample_app\build\outputs\apk"
结果执行
cd "C:\Temp\Test\Install.bat\..\..\apps\app_sample\samples\sample_app\build\outputs\apk"
当前目录是C:\Temp\apps\app_sample\samples\sample_app\build\outputs\apk
在此命令之后,目录名实际上无效Install.bat
在不是目录的路径中。
命令行
cd "%~dp0..\apps\app_sample\samples\sample_app\build\outputs\apk"
好多了,因为它导致执行
cd "C:\Temp\Test\..\apps\app_sample\samples\sample_app\build\outputs\apk"
这也使得C:\Temp\apps\app_sample\samples\sample_app\build\outputs\apk
当前目录,但与上面相比具有完全正确的路径cd
命令行。
为了了解所使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并仔细阅读每个命令显示的所有帮助页面。
-
call /?
...解释%~dp0
and %~f0
.
cd /?
endlocal /?
goto /?
if /?
rem /?
-
set /?
...解释了延迟的环境变量扩展IF and a FOR例子。
setlocal /?
我没有adb安装。所以我只能假设它是一个带有文件扩展名的可执行文件.exe
而不是带有文件扩展名的批处理文件.bat
or .cmd
这需要使用call adb.bat ...
or call adb.cmd ...
在此批处理文件中。