Shaik Md
Shaik Md

Reputation: 601

How to get a Part of the Directory path in a 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.

Upvotes: 5

Views: 15358

Answers (6)

M P
M P

Reputation: 26

%~dp0 returns the full drive letter and path of the current batch file. This can be used in a FOR command to obtain portions of the path:

When run from C:\dir1\dir2\dir3\batch.bat

FOR %%V IN ("%~dp0..\") DO @ECHO %%~dpV

returns C:\dir1\dir2\

This can be extended to continue higher up the path:

FOR %%V IN ("%~dp0..\..\") DO @ECHO %%~dpV

returns C:\dir1\

Source: Microsoft info on batch parameters

Upvotes: 0

dbenham
dbenham

Reputation: 130919

A single line of code does it :-)

If you want the trailing back slash, then

for %%A in ("%~dp0.") do @echo %%~dpA


If you don't want the trailing back slash, then

for %%A in ("%~dp0..") do @echo %%~fA

Upvotes: 1

Arun
Arun

Reputation: 2533

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

:parentfolder
echo %~dp1
goto :eof

Upvotes: 3

SvenS
SvenS

Reputation: 795

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

Upvotes: 1

Anthony Miller
Anthony Miller

Reputation: 15930

You almost had it right. Using %~dp0 grabs the Drive+Full path to your .bat so it will return the folder which your bat file is located in as well.

Since the active directly will be the directory your bat is run from, all you'll need to do is:

@echo off
CD ..
SET SUBDIR=%CD%
ECHO %SUBDIR%

If putting this in a bat script to verify, throw in a PAUSE on a newline to see your output.

Upvotes: -1

MattyG
MattyG

Reputation: 66

@echo off
SET MYDIR=%cd%
cd %MYDIR%\..
SET MYPARENTDIR=%cd%
cd %MYDIR%

Upvotes: 1

Related Questions