在批处理文件中获取上两级目录的路径

5

我希望获取当前位置上两个目录的文件夹路径。

我正在尝试执行以下操作:

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个回答

7
对于每个文件夹,.. 指向它的父文件夹,因此,当前文件夹的两层目录上是 ..\..。现在,为了将相对路径转换为绝对完整路径,我们需要获得指向的文件/文件夹的引用。为了做到这一点,我们可以将相对路径作为参数传递给子例程,或者我们可以使用一个 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
如果您能详细说明这两种方法中的一种的含义,那就太好了。这让我有足够的能力去做我想做的事情,但如果我需要遍历三层,我就不知道如何修改它以满足我的需求了。 - Ian
对于任何想要理解这个答案中 %~f 等内容的人,这个问题的被接受的答案提供了一些有用的语法说明文档 https://dev59.com/KG445IYBdhLWcg3wGmk6 - Solaraeus

4
我今天遇到了同样的问题,但有所不同,我需要从另一个文件夹中调用批处理文件,这是我的解决方法:
@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    +---------------------------------------+

输出结果如下:

在此输入图片描述


(注:该段内容为HTML代码,无需翻译。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接