%% ~dpa的含义?

San*_*osh 6 cmd batch-file

我被允许维护一些批处理文件,我在每个批处理文件的开头重复看到这一行.

FOR /f "usebackq tokens=*" %%a IN ('%0') DO SET this_cmds_dir=%%~dpa
CD /d "%this_cmds_dir%"
Run Code Online (Sandbox Code Playgroud)

有谁知道第一行是做什么的?什么是%% ~dpa?什么是%0?什么是usebackq?

pax*_*blo 19

%~dpa为您提供驱动器和指向的文件的路径%a(当然,使用double,%因为您在脚本中运行).从for /?帮助的底部cmd.exe:

In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
              environment variable and expands %I to the
              fully qualified name of the first one found.
              If the environment variable name is not
              defined or the file is not found by the
              search, then this modifier expands to the
              empty string

The modifiers can be combined to get compound results:

%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
              environment variable for %I and expands to the
              drive letter and path of the first one found.
%~ftzaI     - expands %I to a DIR like output line

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.

%0是运行的批处理文件的名称,usebackq并且tokens=是该for命令的选项.tokens=可用于将单词分配给特定变量,在这种情况下,使用*将整个批次放入%%a.

usebackq更改%0参数周围的引号处理方式.没有它,单引号将运行命令并使用该命令的输出而不是值的值%0.

通过运行上述内容可以找到更多细节for /?.

PATH顺便说一句,这个技巧是在你的路径上找到可执行文件的一种很好的方法.


Kur*_*fle 5

@Santhosh:%0将是当前批处理文件的 调用方式。这可能是任何以下形式:abc.batabc(没有.BAT后缀)..\..\abc.batd:\path\to\abc.bat"e:\path with spaces\to\abc.bat"而且很可能更多一些。

现在,%0用于进一步处理在任何情况下都不起作用,因为它不存在规范形式。您将使用

  • %~0 :删除可能出现的引号%0(如果有);
  • %~n0 :仅使用%0不带后缀的名称;
  • %~nx0 :使用的名称+后缀%0;
  • %~pnx0:使用%0(没有驱动器号)的路径+名称+后缀;
  • %~dpnx0:使用的driveletter + path + name +后缀%0

如果这些参数是文件或目录,则可以使用相同的命令进行清理%1(的第一个参数%0%2等。