Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SET a variable to the path of parent directory on windows?

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?

like image 527
Peter Perháč Avatar asked Jun 10 '09 13:06

Peter Perháč


People also ask

How do I add a variable to a PATH?

To add a path to the PATH environment variableIn the System dialog box, click Advanced system settings. On the Advanced tab of the System Properties dialog box, click Environment Variables. In the System Variables box of the Environment Variables dialog box, scroll to Path and select it.

What do you type in to move to the parent directory?

To change your current working directory to its parent folder (move one branch down the directory tree): > cd .. To move the file data.

How do I change my parent directory?

To change to your home directory, type cd and press [Enter]. To change to a subdirectory, type cd, a space, and the name of the subdirectory (e.g., cd Documents) and then press [Enter]. To change to the current working directory's parent directory, type cd followed by a space and two periods and then press [Enter].


2 Answers

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%
like image 179
Binary Worrier Avatar answered Nov 16 '22 00:11

Binary Worrier


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.

like image 28
RBerteig Avatar answered Nov 15 '22 23:11

RBerteig