A deeper look at the spells (%~dp0) that appear in bat files.

この記事は約4分で読めます。
スポンサーリンク

Things I want to do

Let’s take a closer look at %~dp0, a command that often appears when writing Windows batch files.

What exactly is %~dp0?

If you include %~dp0 in a batch file, it will be replaced with the folder where the batch file was saved.

The following is often found at the top of a .bat file.

cd /d %~dp0

This is to fix the current folder to the folder where the batch file is located, regardless of where the batch file is launched from. (If the batch file contains relative paths, the current folder will affect its operation.)

Incidentally, the /d option changes the current drive at the same time.

スポンサーリンク

The origin of %~dp0

‘%~dp0’ is ‘%0’ with the options ‘~’, ‘d’, and ‘p’ added.

Let’s output the values ​​using F:\bat\test.bat. (@echo off is omitted)

This is the result when executed from Explorer.

%0

%0 stores the path of the executed batch file, enclosed in double quotes. (Note that it contains a relative path when launched from the command prompt, and an absolute path when launched from Explorer.)

F:\bat\test.bat:

echo %0

output:

"F:\bat\test.bat"

Incidentally, %1 will contain the value of the first argument.

F:\bat\test.bat:

echo %0
echo %1

command:

test.bat arg1

output:

"F:\bat\test.bat"
arg1

~

Inserting a ~ between the % and 0 in %0 will remove the ”.

F:\bat\test.bat:

echo %~0

output:

F:\bat\test.bat

d

By inserting ‘d’ between the ‘~’ and ‘0’ in %~0, the drive where the bat file is saved will be output. Note that %d0 will not work.

F:\bat\test.bat:

echo %~d0

output:

F:

p

By inserting ‘p’ between the ‘~’ and ‘0’ in %~0, the folder where the batch file is saved will be output. Note that %p0 will not work.

F:\bat\test.bat:

echo %~p0

output:

\bat\

%~dp0

%~dp0 is the combination shown above.

This will output the connected drive and folder where the batch file is saved.

Therefore, the absolute path of the folder where the .bat file is saved is returned.

F:\bat\test.bat:

echo %~dp0

output:

F:\bat\

コメント

タイトルとURLをコピーしました