在for循环

时间:2015-06-08 05:50:54

标签: batch-file

我正在修改批处理脚本以将文件位置传递给makefile(使用nmake运行)。 for循环应该循环遍历可用的驱动器并搜索该文件(如果之前未设置过)。批量不是我经验丰富的东西,所以希望有人能发现正在发生的事情。

当我在遍历驱动器的for循环之外设置winbison时,变量将通过win_bison.exe的路径设置。当我在for循环中设置它时,我得到“ECHO开启”。我认为那是批处理解析/扩展的方法。我设置了EnableDelayedExpansion但得到了相同的结果。

这是我的代码。

@ECHO OFF
setlocal EnableDelayedExpansion
set currentDir=%cd%
set winbison=
set winflex=

set drives=
for /f "delims=" %%a in ('fsutil fsinfo drives') do @set drives=%%a

REM :~8 is to slice off "Drives: " returned by fsutil
for %%i in (%drives:~8%) do (
    chdir /d %%i
    if not defined [%winbison%] (
        set winbison=
        for /f "delims=" %%a in ('dir win_bison.exe /s /b 2^>nul') do @set winbison=%%a
    @ECHO ON
        echo test
        echo %winbison%
    @ECHO OFF
    )

    if not defined [%winflex%] (
        set winflex=
        for /f "delims=" %%a in ('dir win_flex.exe /s /b 2^>nul') do @set winflex=%%a
    )
)

chdir /d %currentDir%

@ECHO ON
echo %winbison%
... stuff gets passed to nmake.

1 个答案:

答案 0 :(得分:2)

下一个脚本可以工作:

@ECHO OFF
setlocal enableextensions EnableDelayedExpansion
set "currentDir=%cd%"
set "winbison="
set "winflex="

set "drives="
for /f "delims=" %%a in ('fsutil fsinfo drives') do @set "drives=%%a"

REM :~8 is to slice off "Drives: " returned by fsutil
for %%i in (%drives:~8%) do (
  if exist %%iNUL (
    pushd %%i
    if not defined winbison (
      for /f "delims=" %%a in (
        'dir win_bison.exe /s /b 2^>nul') do @set "winbison=%%a"
      echo [debug] %%i winbison=!winbison!
    )

    if not defined winflex (
      for /f "delims=" %%a in (
        'dir win_flex.exe /s /b 2^>nul') do @set "winflex=%%a"
      echo [debug] %%i winflex=!winflex!
    )
    popd
  )
)

echo [debug] winbison=%winbison%
echo [debug] winflex=%winflex%

rem ... stuff gets passed to nmake

在上面的代码段中:

  • 引用所有set "variable=value"以避免(意外遗忘)尾随空格;
  • if exist %%iNUL以避免可能的The device is not ready错误消息;
  • 正确的语法if not defined winbison等;
  • 必要时
  • !variable!而不是%variable%(阅读EnableDelayedExpansion);
  • pushd ... popd对使用而不是cd /D