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 %~dp0This 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 %0Output:
"F:\bat\test.bat"Incidentally, the value of the first command-line argument is stored in %1.
F:\bat\test.bat:
echo %0
echo %1Command:
test.bat arg1Output:
"F:\bat\test.bat"
arg1~
Adding a ~ between the % and 0 in %0 will remove any surrounding quotation marks.
F:\bat\test.bat:
echo %~0Output:
F:\bat\test.batd
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 %~d0Output:
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 %~p0Output:
\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 %~dp0Output:
F:\bat\

comment
Hi! Someone in my Facebook group shared this site with us so I came to take a look.
I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers!
Fantastic blog and superb design.
Hey! This is my first comment here so I just wanted to give a quick
shout out and say I really enjoy reading your posts.
Can you recommend any other blogs/websites/forums that
go over the same subjects? Thanks!
Marvelous, what a webpage it is! This web site provides useful data
to us, keep it up.