开发者

Batch-File to search current absolute path to find a file or directory?

I am trying to search the current directory path and find a certain file or directory that is adjacent to that path. For example: if the current directory of the script is C:\Temp\Dir1\Dir2\Dir3\Dir4\Dir5\Dir6\Test.bat , and if "jars" is a directory located at C:\Temp\jars , then search upwards to find the directory where "jars" is located.

This is how I implemented it but I am wondering if there is an easier/shorter way to do it?

@echo off
SET TITLE=%~nx0
SET SEARCHFOR=jars\Site.jar
SET MYDIR=%~p0
SET MYDRIVE=%~d0
SET DIRCHAIN=%MYDIR:\= %
:: searches first 4 levels of depth but ca开发者_JS百科n be increased if necessary
ECHO Searching in directory chain: %MYDRIVE% %DIRCHAIN%
FOR /F "tokens=1-4 delims= " %%G IN ("%DIRCHAIN%") DO (
  if exist %MYDRIVE%\%SEARCHFOR% (
    SET APPHOME=%MYDRIVE%
    GOTO APPHOMESET
  )
  if exist %MYDRIVE%\%%G\%SEARCHFOR% (
    SET APPHOME=%MYDRIVE%\%%G
    GOTO APPHOMESET
  )
  if exist %MYDRIVE%\%%G\%%H\%SEARCHFOR% (
    SET APPHOME=%MYDRIVE%\%%G\%%H\
    GOTO APPHOMESET
  )
  if exist %MYDRIVE%\%%G\%%H\%%I\%SEARCHFOR% (
    SET APPHOME=%MYDRIVE%\%%G\%%H\%%I
    GOTO APPHOMESET
  )
  if exist %MYDRIVE%\%%G\%%H\%%I\%%J\%SEARCHFOR% (
    SET APPHOME=%MYDRIVE%\%%G\%%H\%%I\%%J
    GOTO APPHOMESET
  )
  GOTO FAILED
)
:FAILED
ECHO Did not discover location of APPHOME containing %SEARCHFOR%
ECHO Searched no deeper than %MYDRIVE%\%%G\%%H\%%I\%%J
:APPHOMESET
SET JREHOME=%APPHOME%\Javasoft\jre
echo APPHOME is %APPHOME%
echo JREHOME is %JREHOME%
pause


The idea is roughly as follows:

  1. Get the path to the batch script as the current working directory.

  2. Concatenate the subdirectory name.

  3. If the resulting path exists, return the path and exit.

  4. If the current working directory is essentially the root directory, return Not found and exit.

  5. Get the parent directory of the current working directory and repeat from step #2.

Here goes:

@ECHO OFF

SET "subdir=%~1"
SET "dir=%~f0"

:loop
  CALL :getdir "%dir%"

  IF EXIST "%dir%\%subdir%\" (
    ECHO %dir%\%subdir%
    GOTO :EOF
  )

  IF "%dir:~-1%" == ":" (
    ECHO Directory "%subdir%" not found.
    GOTO :EOF
  )
GOTO loop

:getdir
SET "dir=%~dp1"
SET "dir=%dir:~0,-1%"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜