I want to get the path of a folder that is 2 directories up from the current location.
I am doing the following:
echo %CD%
set NEW_PATH = ..\..\bin\
echo %PATH%
When I run the above I get the current directory path printed but the NEW_PATH isnt.. It just says ECHO_OFF.
From this link: Batch File: Error in relative path , one level up from the current directory I have also tried
set NEW_PATH = %~dp0..\..\bin\
but still the same problem.
How can I get this directory path?
For each folder, ..
points to its parent folder, so, two levels up from current folder is ..\..
. Now, to convert the relative reference to a absolute full path, we need to get a reference to the pointed file/folder. To do it we can pass the relative reference as an argument to a subroutine or we can use a for
command
@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
EDIT
The submitted code gets relative path for the current directory, not batch file directory. If batch file relative is what you need, try
set "newDir=%~dp0\..\..\bin\"
where %~dp0
is the drive and path of the current batch file (%0
is a reference to the current batch file) and proced with the same/similar code
I had the same problem today but a little different, I had to call a bat from another folder and this is how i solve it:
@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 +---------------------------------------+
And the output is this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With