如何使用批处理文件遍历目录结构

时间:2015-11-19 09:17:44

标签: windows batch-file

我正在编写一个Windows批处理脚本,它编译作为参数传递给它的文件。这就是我想要做的事情:

  1. 转到每个文件位置。
  2. 在当前文件夹中搜索' makefile'。
  3. 如果找到,请运行' make'并爆发,否则转到父文件夹并重复步骤2.
  4. 如果到达当前驱动器的根目录,则退出。
  5. 这是我迄今为止所能提出的:

      

    输入:要编译的文件的完整路径列表。

         

    示例:" D:/dir1/dir2/file1.cxx" " d:/dir1/dir3/file2.cxx"

    @echo off
    REM -- loop over each argument --
    for %%I IN (%*) DO (
       cd %%~dpI
    
       call :loop
    
       echo "After subroutine"
    )
    exit /b
    
    
    :loop
    REM -- NOTE: Infinite loop, breaks out when root directory is reached --
    REM -- or makefile is found                                           --
    for /L %%n in (1,0,10) do (
       if exist "makefile" (
          echo "Building.."
          make -s
          echo "Exiting inner loop"
          exit /b 2
       ) else (
          if "%cd:~3,1%"=="" ( 
            echo "Reached root...exiting inner loop..."
            exit /b 2
          )
    
          REM -- Go to parent directory --
          cd ..
          echo "Searching one level up"
       )
    )
    

    除此之外的一切都有效 - 在遇到第一个' makefile'后,' 退出/ b 2 '导致批处理文件退出。我想要的是只有内循环应该退出。 ' 退出/ b 2 '应该根据this工作,但由于某种原因,它不是。任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您的代码中存在一些问题。不太重要的一点是内循环中当前目录的比较必须通过延迟扩展来完成。现在重要的一个:

无法使用for /L命令中断exit /B循环。虽然循环中exit /B之后的任何命令都不再执行,但循环永远不会结束。您必须使用普通exit命令执行此操作,但当然整个cmd.exe会话也由exit终止,因此解决方案是启动第二个 cmd。 exe会话重新执行由特殊参数控制的相同批处理文件

@echo off

REM If this batch file was re-executed from itself: goto right part
if "%~1" equ ":loop" goto loop

REM -- loop over each argument --
for %%I IN (%*) DO (
   cd %%~dpI

   REM Execute the "subroutine" in a separate cmd.exe session
   cmd /C "%~F0" :loop

   echo "After subroutine"
)
exit /b


:loop
setlocal EnableDelayedExpansion

REM -- NOTE: Infinite loop, breaks out when root directory is reached --
REM -- or makefile is found                                           --
for /L %%n in () do (
   if exist "makefile" (
      echo "Building.."
      make -s
      echo "Exiting inner loop"
      exit
   ) else (
      if "!cd:~3,1!" equ "" ( 
        echo "Reached root...exiting inner loop..."
        exit
      )

      REM -- Go to parent directory --
      cd ..
      echo "Searching one level up"
   )
)

编辑添加了评论

  • 当您使用无限循环时,更清楚的是不在括号中包含任何值;否则你似乎在" 0"增量。

  • 此处显示的链接上显示的EXIT命令说明不正确...

相关问题