在批处理文件中获取路径两个目录

时间:2013-11-06 10:45:46

标签: batch-file path

我想从当前位置获取2个目录的文件夹的路径。

我正在做以下事情:

echo %CD%
set NEW_PATH = ..\..\bin\
echo %PATH%

当我运行上面的命令时,我打印出当前的目录路径但是NEW_PATH不是..它只是说ECHO_OFF。

从此链接:Batch File: Error in relative path , one level up from the current directory我也尝试了

set NEW_PATH = %~dp0..\..\bin\

但仍然是同样的问题。

如何获取此目录路径?

2 个答案:

答案 0 :(得分:5)

对于每个文件夹,..指向其父文件夹,因此,当前文件夹中的两个级别为..\..。现在,要将相对引用转换为绝对完整路径,我们需要获取对指向文件/文件夹的引用。为此,我们可以将相对引用作为参数传递给子例程,或者我们可以使用for命令

@echo off

    setlocal enableextensions disabledelayedexpansion

    set "newDir=..\..\bin"

    rem With a subroutine   
    call :resolve "%newDir%" resolvedDir
    echo %resolvedDir%

    rem With a for - retrieve the full path of the file/folder being
    rem              referenced by the for replaceable parameter
    for %%f in ("%newDir%") do echo %%~ff

    endlocal
    goto :EOF

:resolve file/folder returnVarName
    rem Set the second argument (variable name) 
    rem to the full path to the first argument (file/folder)
    set "%~2=%~f1"
    goto :EOF

编辑

提交的代码获取当前目录的相对路径,而不是批处理文件目录。如果您需要批处理文件相关,请尝试

set "newDir=%~dp0\..\..\bin\"

其中%~dp0是当前批处理文件的驱动器和路径(%0是对当前批处理文件的引用)和具有相同/类似代码的程序

答案 1 :(得分:2)

我今天遇到了同样的问题,但有点不同,我不得不从另一个文件夹中拨打一个蝙蝠,这就是我解决它的方法:

@echo off    

rem tree

rem  <driver>
rem    |
rem   root
rem    |-- A
rem        |-- B
rem            |-- C
rem                |-- test.bat
rem    |-- D
rem        |-- E
rem            |-- testD.bat
rem        |-- testSibling.bat 


rem  take current dir
set "crt_dir=%~dp0"

rem go 3 levels up 
for %%I in ("%crt_dir%\..\..\..") do set "root=%%~fI"

set "sibling=%root%\D

set "insideSibling=%sibling%\E

echo +----------------------------------------------+
echo + current dir   -- "%crt_dir%"
echo + root dir      -- "%root%"
echo + siblling      -- "%sibling%"
echo + insideSibling -- "%insideSibling%"
echo +----------------------------------------------+

call %sibling%\siblingTest.bat
call %insideSibling%\testD.bat

SiblingTest.bat:

echo    +---------------------------------------+
echo    + inside sibling folder "%~dp0"
echo    +---------------------------------------+

testD.bat

echo    +---------------------------------------+
echo    + inside D folder "%~dp0"
echo    +---------------------------------------+

输出是这样的:

enter image description here