The %~dp0 Variable

Reblogged from https://htipe.wordpress.com/2008/10/09/the-dp0-variable/

The %~dp0 (that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.

The variables %0-%9 refer to the command line parameters of the batch file. %1-%9 refer to command line arguments after the batch file name. %0 refers to the batch file itself.

If you follow the percent character (%) with a tilde character (~), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. The d modifier expands to the drive letter and the p modifier expands to the path of the parameter.

Example:  Let’s say you have a directory on C: called bat_files, and in that directory is a file called example.bat. In this case, %~dp0 (combining the d and p modifiers) will expand to C:\bat_files\.

Check out this Microsoft article for a full explanation.

See also this thread on stackoverflow.

This differs from the %cd% variable which is the current directory.

You can easily see the difference by creating the following batch file called, say, test.bat
@echo off
echo The current directory is %cd%
echo The batch file is in %~dp0

If you were to run this from d:\temp by calling c:\bin\test.bat then the output would be
D:\temp>c:\bin\test.bat
The current directory is D:\temp
The batch file is in c:\bin\
D:\temp>

You can use the tilde operator (~) in all sorts of useful ways. You can read more by typing FOR /? from the command prompt.

One useful little trick is to make use of it to get the name (but not full path) of the current folder with:

for %%a in ("%cd%") do set "CurDir=%%~nxa"
which will set the value of CurDir to the name of the current folder.
For example, if run from D:\temp\example then the value of CurDir would be “example” (without the quotes).

Tagged , , . Bookmark the permalink.

About DataHamster

The Data Hamster stores facts and information in its capacious cheek pouches and regurgitates them from time to time.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.