【问题标题】:How to traverse up directory structure using batch file如何使用批处理文件遍历目录结构
【发布时间】:2015-11-19 22:25:31
【问题描述】:

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

  1. 转到每个文件位置。
  2. 在当前文件夹中搜索“makefile”。
  3. 如果找到,运行“make”并断开,否则转到父文件夹并重复第 2 步。
  4. 如果到达当前驱动器的根目录,则退出。

这是我到目前为止所能想到的:

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

示例:“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”后,“exit /b 2”会导致批处理文件退出。我想要的是只有内部循环应该退出。 'exit /b 2' 应该根据this 工作,但由于某种原因它不是。谁能帮我解决这个问题?

【问题讨论】:

  • 我不能用最小的批处理文件重现它,但是你代码中的循环有一个不正确的步骤参数0,应该是1
  • @wOxxOm : 循环步长为 0,因此无限运行。

标签: windows batch-file


【解决方案1】:

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

没有办法用exit /B 命令打破for /L 循环。尽管循环中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"
   )
)

编辑添加了几个 cmets

  • 当您使用无限循环时,更清楚的是不要在括号中包含任何值;否则看起来你在“0”增量中犯了一个错误。

  • 此时出现在您提供的链接上的 EXIT 命令描述不正确...

【讨论】:

    猜你喜欢
    • 2012-02-08
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多