I'm looking at a batch file which defines the following variables:
set _SCRIPT_DRIVE=%~d0
set _SCRIPT_PATH=%~p0
- What do
%~d0
or%~p0
actually mean? - Is there a set of well-known values for things like current directory, drive, parameters to a script?
- Are there any other similar shortcuts I could use?
Some gotchas to watch out for:
If you double-click the batch file
%0
will be surrounded by quotes. For example, if you save this file asc:\test.bat
:Double-clicking it will open a new command prompt with output:
But if you first open a command prompt and call it directly from that command prompt,
%0
will refer to whatever you've typed. If you typetest.bat
Enter, the output of%0
will have no quotes because you typed no quotes:If you type
test
Enter, the output of%0
will have no extension too, because you typed no extension:Same for
tEsT
Enter:If you type
"test"
Enter, the output of%0
will have quotes (since you typed them) but no extension:Lastly, if you type
"C:\test.bat"
, the output would be exactly as though you've double clicked it:Note that these are not all the possible values
%0
can be because you can call the script from other folders:All the examples shown above will also affect
%~0
, because the output of%~0
is simply the output of%0
minus quotes (if any).Another tip that would help a lot is that to set the current directory to a different drive one would have to use
%~d0
first, thencd %~dp0
. This will change the directory to the batch file's drive, then change to its folder.For #oneLinerLovers,
cd /d %~dp0
will change both the drive and directory :)Hope this helps someone.
This code explains the use of the ~tilda character, which was the most confusing thing to me. Once I understood this, it makes things much easier to understand:
It displays the current location of the file or directory that you are currently in. for example; if your batch file was in the desktop directory, then "%~dp0" would display the desktop directory. if you wanted it to display the current directory with the current file name you could type "%~dp0%~n0%~x0".
%~d0
gives you the drive letter of argument 0 (the script name),%~p0
the path.The magic variables
%
n contains the arguments used to invoke the file:%0
is the path to the bat-file itself,%1
is the first argument after,%2
is the second and so on.Since the arguments are often file paths, there is some additional syntax to extract parts of the path.
~d
is drive,~p
is the path (without drive),~n
is the file name. They can be combined so~dp
is drive+path.%~dp0
is therefore pretty useful in a bat: it is the folder in which the executing bat file resides.You can also get other kinds of meta info about the file:
~t
is the timestamp,~z
is the size.Look here for a reference for all command line commands. The tilde-magic codes are described under for.