我正在编写一个CMD脚本来为我的GitHub存储库生成文档标记页面。我决定给脚本一个项目及其文档文件夹的默认目录,如果最终用户想要使用另一个,则必须在下一步之前指定它。
我的代码类似于:
echo.
setlocal enabledelayedexpansion
set projectDirectory=GroupManagementAppServer
set documentationFolder=documentation
rem ask user for confirmation of projectDirectory,documentationFolder to use
choice /m "By default, project directory is %projectDirectory% and documentation is stored in %documentationFolder%. Should I use these?"
rem if no
if %errorlevel% == 2 (
rem get projectDirectory,documentationFolder from user
set /p relativeDocumentationPathname=Please enter relative pathname to the documentation folder:
rem parse input
call :getAbsolutePath %relativeDocumentationPathname%
set documentationFolder=%_absolutePath%
set projectDirectory="%documentationFolder%\.."
)
echo %_absolutePath%
echo %documentationFolder%
echo %projectDirectory%
:getAbsolutePath
SETLOCAL
for %%i in ("%1%") do (
set filedrive=%%~di
set filepath=%%~pi
set filename=%%~ni
set fileextension=%%~xi
)
ENDLOCAL & SET _absolutePath=%filedrive%%filepath%%filename%%fileextension%
到目前为止,当回声完成时,好像documentationFolder
从未重新定义过!到底发生了什么,以及如何解决这个问题,以便我可以实现其余部分并继续实际获取一些文档?
答案 0 :(得分:1)
以下是正确应用delayed expansion的固定代码,减少了子程序并进行了一些小的改进,主要与报价相关:
echo/
setlocal EnableDelayedExpansion
set "projectDirectory=GroupManagementAppServer"
set "documentationFolder=documentation"
rem // Ask user for confirmation of `projectDirectory`, `documentationFolder` to use:
choice /M "By default, project directory is '%projectDirectory%' and documentation is stored in '%documentationFolder%'. Should I use these?"
rem // If no:
if %errorlevel% == 2 (
rem // Get `projectDirectory`, `documentationFolder` from user:
set /P relativeDocumentationPathname="Please enter relative pathname to the documentation folder: "
rem // Parse input:
call :getAbsolutePath "%relativeDocumentationPathname%"
set "documentationFolder=!_absolutePath!"
set "projectDirectory=!documentationFolder!\.."
)
echo %_absolutePath%
echo %documentationFolder%
echo %projectDirectory%
goto :EOF
:getAbsolutePath
setlocal
for /D %%I in ("%~1") do (
set "filespec=%%~fI"
)
endlocal & set "_absolutePath=%filespec%"
答案 1 :(得分:0)
我建议您使用顶部黑条中的SO搜索工具,并尝试查找delayedexpansion
。关于此事有数百项。
从根本上说,当遇到一个块(带括号的系列语句)时,将对整个块进行求值,用变量的当前值代替,一旦完成,就执行代码。
在您的情况下,call echo %%var%%
将显示修改后的值,或者使用子例程中的修改值(如call:arouthethatechosthevalues)来实现新值。