0

i have a folder structure as

c:\name\myname

I wrote a batch file

test.bat

@echo off  
echo %CD%  
echo %CD%\..  
set k=%CD%  
set c=%k%\..  
echo %k%  
echo %c%  
pause

Output

c:\name\myname  
c:\name\myname\\..  
c:\name\myname  
c:\name\myname\\..

Expected Output

c:\name\myname  
c:\name  
c:\name\myname  
c:\name

I have installed windows 8 OS. I want to get parent directory from current directory. May be i don't know the correct syntax to get parent directory.

MC ND
  • 69,615
  • 8
  • 84
  • 126
Kumar
  • 3,782
  • 4
  • 39
  • 87
  • 1
    Similar http://stackoverflow.com/questions/16623780/how-to-get-windows-batchs-parent-folder – elimad Sep 26 '14 at 06:18
  • suppose i have a structure like c:\user\myname\check\test, i need a path from this as c:\user\myname. How can i get it? – Kumar Sep 26 '14 at 06:52

1 Answers1

3

There are two ways to obtain a reference to a file/folder: arguments to batch files and for command. This second option is what we will use here. As it is not clear what parent do you need, let's see how to obtain each

1 - Get parent of current active directory

for %%a in (..) do echo %%~fa

get a reference to the parent of the current active folder inside the for replaceable parameter %%a and once we have the reference, get the full path to it

2 - Get parent of the folder holding the batch file

for %%a in ("%~dp0.") do echo %%~dpa

same idea. %0 is a reference to the current batch file, so %~dp0 is the drive and path where the batch file is stored. This value ends in a backslash, so, to get a reference to the folder an aditional dot is added. Once we have the reference to the folder holding the batch file in %%a, %%~dpa will return the drive and path where the element referenced in %%a is stored. As %%a is the folder holding the batch file, %%~dpa is the parent, the folder where is stored the folder with the batch.

MC ND
  • 69,615
  • 8
  • 84
  • 126