The purpose
You’ve probably seen %~dp0
a lot if you’ve ever written a Windows batch file. Let’s take a closer look at what it does.
First of all, what is %~dp0?
When %~dp0
is used in a batch file, it is replaced by the folder path where the batch file is located.
The following line is often found at the top of a batch file.
cd /d %~dp0
This command ensures that the current directory is always the same as the batch file’s location, no matter where you run it from. (If the batch file uses relative paths, the current directory will affect how it works.)
The /d
option, by the way, is used to change the current drive along with the directory.
origins and composition of %~dp0
%~dp0
is simply %0
with the ~
, d
, and p
modifiers.
Let’s see the output for each value from F:\bat\test.bat
. (@echo off
will be omitted.)
These are the results from running the file via Explorer.
%0
%0
contains the path to the executed batch file, enclosed in double quotes. Be aware that this will be a relative path if you run it from the command prompt, but an absolute path if you run it from File Explorer.
F:\bat\test.bat:
echo %0
Output:
"F:\bat\test.bat"
Incidentally, the value of the first command-line argument is stored in %1
.
F:\bat\test.bat:
echo %0
echo %1
Command:
test.bat arg1
Output:
"F:\bat\test.bat"
arg1
~
Adding a ~
between the %
and 0
in %0
will remove any surrounding quotation marks.
F:\bat\test.bat:
echo %~0
Output:
F:\bat\test.bat
d
To output the drive where the batch file is located, you need to place a d
between the ~
and 0
, like %~d0
. Be aware that %d0
will not work.
F:\bat\test.bat:
echo %~d0
Output:
F:
p
Adding a p
between ~
and 0
in %~0
will output the folder where the batch file is stored. Be careful, as %p0
will not work.
F:\bat\test.bat:
echo %~p0
Output:
\bat\
%~dp0
%~dp0
is a combination of the modifiers mentioned above.
It outputs the drive letter and folder path of the directory where the batch file is stored.
As a result, you get the absolute path to the batch file’s folder.
F:\bat\test.bat:
echo %~dp0
Output:
F:\bat\
comment