17

Given that the current directory, %CD% is

C:\Parent\Child

In a batch file, how can I get the value Child in to a variable?

thanks

4 Answers 4

28
for %%a in (.) do set currentfolder=%%~na
echo %currentfolder%

From here: https://superuser.com/questions/160702/get-current-folder-name-by-a-dos-command

Sign up to request clarification or add additional context in comments.

1 Comment

It is almost correct, but it doesn't print the extension of the directory. E.g: in case of c:\parent\child.01. An additional 'x' character should be added to work correctly: currentfolder=%%~nxa
3

Here is the answer

for %%a in ("%cd%") do set folder=%%~na
echo.%folder%
pause

1 Comment

This should not work! Supposedly, the %~ modifiers can only be used on file or folder names, but "%cd%" is a STRING! Apparently, the string is processed as a name no matter its contents. Try this: for %a in ("@:\one;\two()\three=+") do echo %~da %~na %~fa
1

or you can do something like this

@ECHO OFF
FOR %%a IN (.) DO SET currentfolder=%%~nxa
ECHO %currentfolder%

Comments

0

@manojlds's answer is not correct for all cases.

The %%~nI shortcut works fine for files, but not for directories.

Example:

C:\a..o\ex.bat

@ECHO OFF
FOR %%a IN (.) DO SET currentfolder=%%~na
ECHO %currentfolder%

If I execute this batch file from its location, the output is "a.":

C:\a..o\>ex.bat
a.

Solution:

A possible solution is the following:

C:\sol.bat

@ECHO OFF
SETLOCAL
SET cwd="\%~f1"
SET name=""
:extract
    SET char="%cwd:~-2,-1%"
    IF NOT %char%=="\" (
        SET cwd="%cwd:~1,-2%"
        SET name="%char:~1,-1%%name:~1,-1%"
        GOTO :extract
    )
ECHO %name%
ENDLOCAL

Tests:

C:\>sol.bat "@!%#"
"@!%#"
C:\>sol.bat a..o
"a..o"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.