Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Part of the Directory path in a batch file

Tags:

batch-file

I have a BAT file in a directory

D:\dir1\dir2\getpath.bat

when i run the bat with the below code it prints

D:\dir1\dir2\

i want only the path D:\dir1\

The directory structure is not fixed , need the complete directory path other than the current directory in which BAT file resides.

@echo off
SET SUBDIR=%~dp0
ECHO %SUBDIR% 

tried using delims in a for loop but it didnt help.

like image 623
Shaik Md Avatar asked Oct 09 '22 22:10

Shaik Md


2 Answers

@echo off
setlocal
SET SUBDIR=%~dp0
call :parentfolder %SUBDIR:~0,-1% 
endlocal
goto :eof

:parentfolder
echo %~dp1
goto :eof
like image 147
Arun Avatar answered Oct 13 '22 10:10

Arun


If it's the parent directory of the directory your script resides in you want, then try this:

@echo off
SET batchdir=%~dp0
cd /D "%batchdir%.."
echo %CD%
cd "%batchdir%"

(untested, please comment if there are problems)

Note that this will, of course, change nothing if your batch resides in your drive root (as in F:\) ;) If you'd like a special output if that's the case, you should test %CD% against %batchdir% before the echo.

EDIT: Applied patch, see comment by @RichardA

like image 39
SvenS Avatar answered Oct 13 '22 12:10

SvenS