Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the name of the parent folder in a command prompt?

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.

like image 355
Bernhard Hofmann Avatar asked Jun 09 '10 07:06

Bernhard Hofmann


People also ask

How do I go back a parent directory in cmd?

When you want to go back, type cd - and you will be back where you started.

What is the parent directory?

Every directory, except the root directory, lies beneath another directory. The higher directory is called the parent directory, and the lower directory is called a subdirectory.

What is the parent folder of a file?

A folder that is one level up from the current directory in a file hierarchy. In a DOS, Windows or Mac command line, two dots (..) refer to the preceding folder/directory level.


2 Answers

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%
like image 176
pmod Avatar answered Sep 27 '22 16:09

pmod


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.

like image 27
Blair Holloway Avatar answered Sep 27 '22 15:09

Blair Holloway