[Bat] How to get the path of the batch file itself! Let's master "% ~ 0".


Hello!This time, I will summarize how to specify the path that is often used in the batch file.

You can easily get your own path by using "% ~ 0" in the batch file.
This is a method that I often use, so I would like to introduce it all together.

Use% ~ 0

You can get the path of the batch file itself by entering the d, p, n, x symbols between% ~ and 0, which is a method that can be used only in the batch file.

If you create a batch file called C: \ Users \ User \ Desktop \ hoge.bat, you can get your own path in the following form.

-Full path of the file: C: \ Users \ User \ Desktop \ hoge.bat

% ~ D0
-Only the drive with the file: C:

% ~ p0
-Path without file drive and file name: \ Users \ User \ Desktop \

% ~ n0
-File name only: hoge

% ~ x0
-Extension only: .bat

In this way, when a symbol is inserted between% ~ and 0, a part of the corresponding path is converted.

perhapsdrive "d",path "p",name "n", exI think it's the "x" of tend.
* This may be my belief ... I remember it because it's easy to remember.

Use in combination

It is possible to obtain the desired path by combining the above alphabets.

% ~ dp0
-Current folder of files: C: \ Users \ User \ Desktop \

% ~ nx0
-File name with extension: hoge.bat

% ~ dpnx0
-Full path (equivalent to% ~ 0): C: \ Users \ User \ Desktop \ hoge.bat

It seems that these three are often used.

Even if the order is out of order?

I don't know why this is the specification, but it seems to work properly as a path even if the order is wrong.

% ~ xdpn0
% ~ dpxn0
% ~ xnpd0
% ~ dpnx0

All of these output the same full path as% ~ 0: C: \ Users \ User \ Desktop \ hoge.bat

Well, since it is a list of alphabets, is it a consideration to move in no particular order?

Actually use

These acquisition methods do not make much sense on their own.
I think that most of them are put in a variable with the set command or displayed with the echo command.

After that, it is convenient when moving the current folder to the same folder as the batch file.
You can prevent the relative path from shifting when the administrator executes it.

Sample code

@ Echo off
cd / d% ~ dp0
set FOLDER_PATH =% ~ 0

echo% FOLDER_PATH% is the same as% ~ dpnx0


thisYou can move the current folder to the same location as the batch by executing.
Also, in Set, the full path is entered in the variable, and the same full path as% ~ dpnx0 is output.

It's a little difficult to understand at first, but it's very convenient once you get used to it, so I hope you find it useful.


Translate »
I copied the title and URL