Jack Chung
Jack Chung

Reputation: 5

How to get the full path of the parent directory / upper directory of the the current directory in command line

as shown below, I have a batch file named 'Current Path.bat' being stored in 'C:\A\B\'.

C:\A\B\Current Path.bat

What I want to do is to output the full path of the parent directory / upper directory of the the current directory (i.e. where the batch file is being stored / executed).

The expected result in this case should be:

C:\A\

Currently I have figured out a work-around for this, but it is not the perfect one. I am wondering if there is a better solution for this.

My work-around for the moment:

@echo off 
set current_path=%cd%
echo Current Path: %current_path% 
cd ..
set upper_path= %cd%
echo Upper Path: %upper_path%

The result is as below:

C:\>cd a
C:\A>cd b
C:\A\B>"Current Path.bat"
Current Path: C:\A\B
Upper Path:  C:\A

The result of my work-around

Upvotes: 0

Views: 1865

Answers (1)

AlexP
AlexP

Reputation: 4430

There is nothing wrong with your approach; to avoid changing the current directory you can do, for example,

pushd ..
set upper_path=%CD%
popd

If you want to avoid changing directories even for an instant you can use a for:

for %%x in ("%CD%") do set upper_path=%%~dpx

Which of the two is more readable is your choice.

Upvotes: 6

Related Questions