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.
When you want to go back, type cd - and you will be back where you started.
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.
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.
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%
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With