%% ~dpa的含义?

时间:2010-09-08 11:05:28

标签: batch-file cmd

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

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

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

2 个答案:

答案 0 :(得分:16)

%~dpa为您提供%a指向的文件的驱动器和路径(使用双%,因为您在脚本中运行)。在for /?的{​​{1}}帮助的底部:

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.

cmd.exe是正在运行的批处理文件的名称,%0usebackqtokens=命令的选项。 for可用于将字词分配给特定变量,在这种情况下,使用tokens=将整个批次放入*

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

运行前面提到的%0

可以找到更多详细信息

顺便说一句,for /?法案是nifty way在您的路径上查找可执行文件。

答案 1 :(得分:4)

@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等,以防这些参数是文件或目录。