Как в bat файле получить путь к его местоположению

dp0 , которая выводит путь к той директории, откуда был запущен bat файл. К примеру, вы можете создать такой вот простой bat файл, со следующим содержанием:
В результате выполнения такого файла, будет выводиться значение переменной %
dp0, которое содержит в себе путь к той директории, в которой этот самый файл расположен. Например, если сохранить этот bat файл на рабочий стол пользователя Windows 10 с именем User, то вывод при выполнении bat файла будет следующий:
What does %
dp0 very useful, and I use it a lot to make my batch files more portable.
But the label itself seems very cryptic to me. What is the
doing? Does dp mean drive and path? Does the 0 refer to %0 , the path to the batch file that includes the file name?
Or it is just a weird label?
I’d also like to know if it is a documented feature, or something prone to be deprecated.
dp0. Maybe because it has %
d0 on it's title instead of %
dp0 . Usually I find that the top hits refer to content on SO.
7 Answers 7
in the command-line gives help about this syntax (which can be used outside FOR, too, this is just the place where help can be found).
In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:
The modifiers can be combined to get compound results:
In the above examples %I and PATH can be replaced by other valid values. The %
syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.
There are different letters you can use like f for «full path name», d for drive letter, p for path, and they can be combined. %
is the beginning for each of those sequences and a number I denotes it works on the parameter %I (where %0 is the complete name of the batch file, just like you assumed).
dp0 as the working directory of the C# program and NOT the location of the batch file. If you use Process.Start to run cmd.exe which in turn runs the batch file (e.g. using arguments /C foo.bat ) then all is well. I suspect this is to do with how and where PATH is expanded. You can set the WorkingDirectory of the Process to fix this problem.
(First, I’d like to recommend this useful reference site for batch: http://ss64.com/nt/)
dp0 (that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.
The variables %0-%9 refer to the command line parameters of the batch file. %1-%9 refer to command line arguments after the batch file name. %0 refers to the batch file itself.
If you follow the percent character ( % ) with a tilde character (
), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. The d modifier expands to the drive letter and the p modifier expands to the path of the parameter.
Example: Let’s say you have a directory on C: called bat_files , and in that directory is a file called example.bat . In this case, %
dp0 (combining the d and p modifiers) will expand to C:\bat_files\ .
Check out this Microsoft article for a full explanation.
Also, check out this forum thread.
And a more clear reference from here:
%CmdCmdLine% will return the entire command line as passed to CMD.EXE
%* will return the remainder of the command line starting at the first command line argument (in Windows NT 4, %* also includes all leading spaces)
dn will return the drive letter of %n (n can range from 0 to 9) if %n is a valid path or file name (no UNC)
pn will return the directory of %n if %n is a valid path or file name (no UNC)
nn will return the file name only of %n if %n is a valid file name
xn will return the file extension only of %n if %n is a valid file name
fn will return the fully qualified path of %n if %n is a valid file name or directory
ADD 1
Just found some good reference for the mysterious
string is called percent tilde operator. You can find it in situations like: %
string is called colon tilde operator. You can find it like %SOME_VAR:
ADD 2 — 1:12 PM 7/6/2018
%1-%9 refer to the command line args. If they are not valid path values, %
dp9 will all expand to the same value as %
dp0 . But if they are valid path values, they will expand to their own driver/path value.
Что значит dp0 в bat
dp0 (that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.
The variables %0-%9 refer to the command line parameters of the batch file. %1-%9 refer to command line arguments after the batch file name. %0 refers to the batch file itself.
If you follow the percent character (%) with a tilde character (
), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. The d modifier expands to the drive letter and the p modifier expands to the path of the parameter.
Example: Let’s say you have a directory on C: called bat_files, and in that directory is a file called example.bat. In this case, %
dp0 (combining the d and p modifiers) will expand to C:\bat_files\.
Check out this Microsoft article for a full explanation.
See also this thread on stackoverflow.
This differs from the %cd% variable which is the current directory.
You can easily see the difference by creating the following batch file called, say, test.bat
@echo off
echo The current directory is %cd%
echo The batch file is in %
If you were to run this from d:\temp by calling c:\bin\test.bat then the output would be
D:\temp>c:\bin\test.bat
The current directory is D:\temp
The batch file is in c:\bin\
D:\temp>
You can use the tilde operator (
) in all sorts of useful ways. You can read more by typing FOR /? from the command prompt.
One useful little trick is to make use of it to get the name (but not full path) of the current folder with:
for %%a in («%cd%») do set «CurDir=%%
nxa»
which will set the value of CurDir to the name of the current folder.
For example, if run from D:\temp\example then the value of CurDir would be “example” (without the quotes).
Что означает %
dp0 очень полезно, и я использую его много, чтобы сделать мои пакетные файлы более портативными.
но сам ярлык кажется мне очень загадочным. что такое
делаешь? делает dp средний диск и путь? делает ли 0 смотрите %0 путь к пакетному файлу, который включает имя файла?
или это просто странная метка?
Я также хотел бы знать, если это документированная функция, или что-то склонное быть устаревшим.
7 ответов:
вызов
в командной строке дает справку об этом синтаксисе (который может быть использован снаружи, потому что это просто место, где можно найти помощь).
кроме того, замена для ссылки на переменные были улучшены. Теперь вы можете использовать следующие дополнительные функции синтаксис:
модификаторы могут быть объединены, чтобы получить составные результаты:
в приведенных выше примерах %I и PATH мочь заменить другими допустимыми значениями. Синтаксис %
завершается допустимым Для имени переменной. Комплектация верхний регистр имена переменных, такие как %I, делают его больше читаемый и избегает путаницы с модификаторы, которые не дело чувствительный.
есть разные буквы, которые вы можете использовать, как f для «полный путь», d для буквы диска, p на пути, и они могут быть объединены. %
начало для каждой из этих последовательностей и ряд I обозначает, что он работает на параметр %I (где %0 полное имя пакетного файла, как вы и предположили).
(во-первых, я хотел бы рекомендовать этот полезный справочный сайт для партии: http://ss64.com/nt/)
тогда просто еще одно полезное объяснение:http://htipe.wordpress.com/2008/10/09/the-dp0-variable/
переменная %
dp0 (это ноль) при ссылке в Windows пакетный файл будет расширен до dРив письмо и path этой партии файл.
переменные %0 — % 9 относятся к параметрам командной строки пакета файл. %1-%9 см. аргументы командной строки после имени пакетного файла. %0 относится к самому пакетному файлу.
если вы следуете символу процента ( % ) с символом Тильды (
), можно вставить модификатор(ы) перед номером параметра, чтобы изменить путь к переменной. Д модификатор распространяется на диск буква и модификатор p расширяются до пути параметр.
пример: Допустим, у вас есть каталог на C: называется bat_files, и в этом каталоге находится файл с именем example.летучая мышь. В этом случае, %
dp0 (объединение модификаторов d и p) будет расширяться до C:\bat_files.
проверить этой статье для полного объяснения.
кроме того, проверьте эта ветка форума.
и более четкая ссылка от здесь:
%CmdCmdLine% вернет всю командную строку, как передано в CMD.EXE
%* возвращает остаток командной строки, начиная с первого аргумента командной строки (в Windows NT 4, % * также включает все начальные пробелы)
dn вернет букву диска %n (n может варьироваться от 0 до 9), Если %n-допустимый путь или имя файла (нет UNC)
pn вернет каталог %n, если %n-допустимый путь или имя файла (без UNC)
nn будет возвращать имя файла только %N, если %n является допустимым именем файла
xn возвращает расширение файла только %n, если %n-допустимое имя файла
fn возвращает полный путь %n, если %n-допустимое имя файла или каталог
добавить 1
нашел хорошую ссылку для таинственная
строка называется процентов Тильда оператора. Вы можете найти его в таких ситуациях, как: %
ДОБАВИТЬ 2 — 1:12 ВЕЧЕРА 7/6/2018
%1-%9 смотрите в книге Command аргументов строка. Если они не допустимые значения: путь, %
dp9 все будет расширяться до того же значения, что и %
dp0 . Но если они are допустимые значения пути, они будут расширяться, чтобы собственные водителя/пути.
например: (партия.летучая мышь)
dp специальный синтаксис между % и 0 в основном говорит, чтобы расширить переменной %0 показать букву диска и путь, который дает вам текущий каталог, содержащий пакетный файл!
еще один совет, который бы очень помог, — это установить текущий каталог в другой диск можно было бы использовать %
d0 во-первых, тогда cd %
dp0 . Это изменит каталог на диск пакетного файла, а затем перейдите в его папку.
альтернативно, для #oneLinerLovers, как указал @Omni в комментариях cd /d %
dp0 изменится как диск, так и каталог:)
надеюсь, это поможет кто-то.
dp0 расширяется до текущего пути к каталогу запущенного пакетного файла.
чтобы получить четкое представление, давайте создадим пакетный файл в каталоге.
C:\script\test.летучая мышь
когда вы запустите его из командной строки, вы увидите такой результат:
отличный пример из портативной пусковой установки Strawberry Perl:
Не уверен, что отрицательный 1 делает там сам, но это работает удовольствие!
пример был бы хорош — вот тривиальный
в нем перечислены только расширения каждого файла в текущей папке
для более полезных комбинаций переменных (также перечисленных в предыдущем ответе) из командной строки выполните: HELP FOR который содержит этот фрагмент
модификаторы можно объединять для получения сложных результатов: