views:

450

answers:

3

Hello,

Struggling with command line again, I have figure out that I can store the current working directory in a variable like so:

SET current=%cd%

How would I set parent though? SET parent=%..% does not work, as it echoes %..%

Basically, calling a batch script C:\a\b\myscript.bat with the following contents:

@echo off
set current=%cd%
echo %current%

prints C:\a\b and I should like to set a variable parent so that it would print C:\a without changing the current working directory to ..

Is this possible?

+8  A: 

Move up a directory, remembering the current, set the parent, and then pop down a directory, back to where you started

@echo off
set current=%cd%
pushd ..
set parent=%cd%
popd

echo current %current%
echo parent %parent%
Binary Worrier
Perfect! I now remember seeing the pushd and popd somewhere but it totally slipped my mind. Thanks for your help.
Peter Perháč
You're more than welcome mate :)
Binary Worrier
+1  A: 

Use

pushd targetFolder
set current=%cd%
popd

Pushd/popd maintain a stack of previously visited directories.

Richard
thank you, too, for your help
Peter Perháč
+2  A: 

You could also do something like this:

set current=%CD%
set parent=%CD%\..

It doesn't give you the canonical name of the parent, but it should always be a valid path to the parent folder. It will also be somewhat faster than the solutions involving pushd and popd, but that won't be the primary consideration in a batch file.

Edit: Note that all of the solutions so far, including mine here, will have problems if the current folder is the root of a drive. There is no clean and easy way out of that one, since there really is no parent of a drive visible to user mode.

RBerteig
That's another way to look at it. As to your edit, both ways seem to have no problems with the 'current' being the root of a drive. C:\ cd .. won't take you one level higher but stays at C:\ without braking, and technically C:\ is the parent of C:\ so that's cool. Won't be using this from root anyway ;)
Peter Perháč
Its just a source of a discontinuity, or a loop that fails to halt, so I thought it worth mentioning.
RBerteig