batch files: getting directory and parent directory
Posted by jpluimers on 2011/08/09
In some situations, batch files are the only thing you have.
In this case, I needed the parent directory of a batchfile.
i.e. not the directory of the batch file itself, but the
echo batchfile=%0 echo full=%~f0 setlocal ::http://stackoverflow.com/questions/636381/what-is-the-best-way-to-do-a-substring-in-a-batch-file set Directory=%~dp0 echo Directory=%Directory% :: strip trailing backslash set Directory=%Directory:~0,-1% echo %Directory% :: ~dp does not work for regular environment variables: :: set ParentDirectory=%Directory:~dp% set ParentDirectory=%Directory:~dp% :: ~dp only works for batch file parameters and loop indexes for %%d in (%Directory%) do set ParentDirectory=%%~dpd echo ParentDirectory=%ParentDirectory% endlocal
The point is that the %~dp0 trick as explained in this StackOverflow answer on substrincgs in batch files only works for batch file parameters (starting with a single percentage sign: %0, %1, %4, etc) or for-loop indexes (starting with double percentage signs: %%1, %%d, etc). They don’t work for getting path portions of regular environment variables.
So I used the substring trick (as explained in the same answer), and then used a for loop (which will have one iteration) to get the path portion.
Note: The substrings trick only works on regular environment variables, not on parameters and loop indexes.
Note 2: I used setlocal/endlocal so the changed environment variables stay local to the batch file and won’t leak out to your command-prompt. If you need the value there, then remove the setlocal/endlocal, or use an “endlocal & set” command on a single line.
It outputs this:
C:\TEMP\bin>show-parent-directory.bat
C:\TEMP\bin>echo batchfile=show-parent-directory.bat
batchfile=show-parent-directory.batC:\TEMP\bin>echo full=C:\TEMP\bin\show-parent-directory.bat
full=C:\TEMP\bin\show-parent-directory.batC:\TEMP\bin>setlocal
C:\TEMP\bin>set Directory=C:\TEMP\bin\
C:\TEMP\bin>echo Directory=C:\TEMP\bin\
Directory=C:\TEMP\bin\C:\TEMP\bin>set Directory=C:\TEMP\bin
C:\TEMP\bin>echo C:\TEMP\bin
C:\TEMP\binC:\TEMP\bin>for %d in (C:\TEMP\bin) do set ParentDirectory=%~dpd
C:\TEMP\bin>set ParentDirectory=C:\TEMP\
C:\TEMP\bin>echo ParentDirectory=C:\TEMP\
ParentDirectory=C:\TEMP\C:\TEMP\bin>endlocal






Pinky said
Thanks for writing this post. I had similar problem, did extensive google but did not find a solution until I landed here.
Worked very well for me !
shorter version of batch file: getting directory and parent directory « The Wiert Corner – irregular stream of stuff said
[…] via: batch files: getting directory and parent directory « The Wiert Corner – irregular stream of stuf…. […]