我想从当前位置获取一个文件夹的路径,该文件夹是2个目录.
我正在做以下事情:
echo %CD%
set NEW_PATH = ..\..\bin\
echo %PATH%
Run Code Online (Sandbox Code Playgroud)
当我运行上面的命令时,我打印了当前的目录路径但是NEW_PATH不是..它只是说ECHO_OFF.
从这个链接:批处理文件:相对路径错误,从我也尝试过的当前目录向上一级
set NEW_PATH = %~dp0..\..\bin\
Run Code Online (Sandbox Code Playgroud)
但仍然是同样的问题.
我怎样才能获得此目录路径?
对于每个文件夹,..
指向其父文件夹,因此,从当前文件夹向上两级..\..
.现在,要将相对引用转换为绝对完整路径,我们需要获取对指向文件/文件夹的引用.为此,我们可以将相对引用作为参数传递给子例程,或者我们可以使用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
Run Code Online (Sandbox Code Playgroud)
编辑
提交的代码获取当前目录的相对路径,而不是批处理文件目录.如果您需要批处理文件相关,请尝试
set "newDir=%~dp0\..\..\bin\"
Run Code Online (Sandbox Code Playgroud)
其中%~dp0
是当前批处理文件的驱动器和路径(%0
是对当前批处理文件的引用)和具有相同/类似代码的过程