views:

70

answers:

3

I'm in a Windows Command Line and want the parent folder in a variable.

Assuming current directory is "C:\foo\bar", how can I get the value "bar"?

I'm expecting something like a "find last backslash in CD and that's it".

And please, no powershell references; I want plain old Windows Command Line operations.

+1  A: 

This appears to get the current directory name, and stores it in the environment variable bar:

for %i in (%CD%) do set bar=%~ni

This works because %CD% contains the current directory, and %~n strips the output of the for loop (looping for one value, %CD%) to the 'file name' portion.

(Note, if you're using this in a batch file, use %%i and %%~ni instead.)

This doesn't, however, work for the root directory of a drive, it will instead unset bar, as %~ni will evaluate to nothing.

Blair Holloway
It also breaks the folder name if the folder name contains a period (full stop). But otherwise, it's ace!
Bernhard Hofmann
+2  A: 

My solution uses substitution and works for root directory as well:

call set PARENT_DIR=%CD%
set PARENT_DIR=%PARENT_DIR:\= %
set LAST_WORD=
for %%i in (%PARENT_DIR%) do set LAST_WORD=%%i
echo %LAST_WORD%
Pmod
You beat me to it and you have a nicer solution - I'm not sure mine works for root folders.
Bernhard Hofmann
A: 

Pmod has a neater solution; I'm not sure mine works for root folders. But I thought I'd include it here for people to see.

set myPath=%cd%
pushd ..
set parentPath=%cd%
popd
echo myPath = "%myPath%"
echo parentPath = "%parentPath%"
call set myDir=%%myPath:%parentPath%\=%%
echo myDir = "%myDir%"
Bernhard Hofmann